This commit is contained in:
Saturneric 2020-08-31 23:48:40 +08:00
parent 6b3371ca89
commit c90dc13350
2 changed files with 135 additions and 0 deletions

72
Client/main.c Normal file
View File

@ -0,0 +1,72 @@
//
// main.c
// presonal poster client
//
// Created by Eric on 16-2-17.
// Copyright (c) 2016年 Bakantu Eric. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#define PROT 8884
#define N_MAX 256
int main(int argc, const char * argv[]) {
int sockfd;
int len;
struct sockaddr_in addr;
int newsockfd;
char buf[N_MAX];
int len2;
char rebuf[N_MAX];
int i,key;
char ch;
printf("Input key: (<= 6)");
scanf("%d",&key);
getchar();
while (1){
sockfd = socket(AF_INET, SOCK_STREAM, 0);
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = PROT;
len = sizeof(addr);
newsockfd = connect(sockfd, (struct sockaddr *)&addr, len);
if (newsockfd == -1){
printf("Fail in connect the Server!");
return -1;
}
printf("SEND: ");
i = 0;
while ((ch = getchar()) != '\n'){
buf[i] = ch;
i++;
}
buf[i] = '\0';
if (!strcmp(buf, "quit")) break;
for (i = 0; i < strlen(buf); i++){
if (buf[i] == ' ') buf[i] = '_';
buf[i] += key;
}
len2 = sizeof(buf);
send(sockfd, buf, len2, 0);
usleep(1000);
recv(sockfd, rebuf, N_MAX, 0);
rebuf[strlen(rebuf)+1] = '\0';
printf("Receive message: %s\n",rebuf);
close(sockfd);
}
return 0;
}

63
Server/main.c Normal file
View File

@ -0,0 +1,63 @@
//
// main.c
// personal poster
//
// Created by Eric on 16-2-17.
// Copyright (c) 2016年 Bakantu Eric. All rights reserved.
//
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#define PROT 8096
int main(int argc, const char * argv[]) {
char string_send[255] = "Success";
char buf[256];
int s_fd, c_fd;
int s_len, c_len;
struct sockaddr_in s_addr;
struct sockaddr_in c_addr;
if ((s_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
printf("Socket failed");
return -1;
}
s_addr.sin_family = AF_INET;
s_addr.sin_addr.s_addr = htonl(INADDR_ANY);
s_addr.sin_port = PROT;
s_len = sizeof(s_addr);
if (bind(s_fd, (struct sockaddr *)&s_addr, s_len) == -1) { printf("Bind failed!"); return -1;}
listen(s_fd, 10);
int key;
pid_t pid;
printf("Input key: (<= 6)");
scanf("%d",&key);
while(1){
c_len = sizeof(c_addr);
c_fd = accept(s_fd, (struct sockaddr *)&c_addr, (socklen_t*__restrict)&c_len);
printf("#+# %s Login\n",inet_ntoa(c_addr.sin_addr));
pid=fork();
if(pid==-1)
{
printf("Fork failed");
}
if (pid == 0){
recv(c_fd, buf, 256, 0);
buf[strlen(buf)+1] = '\0';
printf("#!#Receive message: %s From %s\n",buf,inet_ntoa(c_addr.sin_addr));
write(c_fd,buf,sizeof(buf));
send(c_fd, string_send, sizeof(string_send), 0);
}
if(pid>0){
close(c_fd);
}
}
return 0;
}