今天又学习了socket,还是不停地出错,还是记录在这,有时间就翻出来看看(我恨那些奇怪的函数名)。
这是个简单的 客户-服务器 小列子
客户端向服务端发送一个数字字符,服务端将其转换为数字,并计算其平方,然后送给客户端。没有对输入环节进行纠错处理。
稍微改改,就可以变成多线程或多进程的服务端。
server.c
#include<sys/types.h>
#include<sys/socket.h>
#include<stdio.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char x;
int xx;
char str[256];
int server_socktfd, client_socktfd;
int server_len, client_len;
struct sockaddr_in client_address;
struct sockaddr_in server_address;
memset(&client_address, 0, sizeof(client_address));
server_socktfd = socket(AF_INET, SOCK_STREAM, 0);
//printf("%d\n",server_socktfd);
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = inet_addr("127.0.0.1");
server_address.sin_port = 9734;
server_len = sizeof(server_address);
bind(server_socktfd, (struct sockaddr *)&server_address, server_len);
if(listen(server_socktfd,5) < 0 ){
perror("start listen failed");
exit(1);
}
while(1) {
printf("Server waiting for connecting\n");
client_len = sizeof(client_address);
client_socktfd = accept(server_socktfd, (struct sockaddr*)&client_address, &client_len);
printf("new connect\n");
if(client_socktfd < 0){
perror("accept failed");
exit(1);
}
printf("Client %d connected\t",client_socktfd);
printf("IP:%s PORT:%d\n\n",*(inet_ntoa(client_address.sin_addr)), client_address.sin_port);
<span style="white-space:pre"> </span>/**
<span style="white-space:pre"> </span>这句输出很奇怪,今天的错误就出在这里,原因是类型不匹配,出现段错误,可是为什么会波及到上一个输出语句也不能输出呢,让我很无解,还以为我的accept方法的参数有问题,对了老半天,最后调试才发现错误的根源。不过,有一点好处是,让我对这段知识的影响深刻不少。所以说,当觉得某个知识点觉得难理解的时候,就写个错的程序,然后慢慢改,这也是个对知识加深了解的不错的方法。
<span style="white-space:pre"> </span>*/
<span style="white-space:pre"> </span>
while(1) {
printf("wait calculating....\n\n");
read(client_socktfd, &x, sizeof(x));
memset(str,0,sizeof(str));
if(x!='#') {
xx = x - '0';
xx = xx*xx;
sprintf(str,"The result of %c * %c is %d", x, x, xx);
} else {
strcpy(str,"See you !");
}
write(client_socktfd, str, sizeof(str));
if(x == '#'){
printf("client %d closed\n\n",client_socktfd);
close(client_socktfd);
break;
}
}
}
}
client.c
#include<sys/types.h>
#include<sys/socket.h>
#include<stdio.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
int socktfd;
int len;
struct sockaddr_in address;
int result;
char ch;
char str[256];
socktfd = socket(AF_INET, SOCK_STREAM, 0);
//printf("%d\n",socktfd);
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr("127.0.0.1");
address.sin_port = 9734;
len = sizeof(address);
result = connect(socktfd, (struct sockaddr*)&address, len);
if(result == -1) {
perror("connect error");
exit(1);
} else if(result == 0) {
printf("Connecte success\n");
while(1) {
printf("input a number(quit by #):");
ch = getchar();
while(getchar()!='\n')
;
memset(str, 0, sizeof(str));
write(socktfd, &ch, sizeof(ch));
read(socktfd, str, sizeof(str));
printf("from server: %s\n",str);
if(ch == '#') {
break;
}
}
close(socktfd);
}
exit(0);
}