linux socket通信
服务器端
#include
#include
#include
#include
#include
#include
#include
#include
#include
int main(int argc, const char* argv[])
{
int lfd = socket(AF_INET, SOCK_STREAM, 0);
if(lfd == -1)
{
perror("socket error");
exit(1);
}
struct sockaddr_in serv_addr;
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(9999);
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
int ret = bind(lfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
if(ret == -1)
{
perror("bind error");
exit(1);
}
ret = listen(lfd, 64);
if(ret == -1)
{
perror("listen error");
exit(1);
}
struct sockaddr_in cline_addr;
socklen_t clien_len = sizeof(cline_addr);
int cfd = accept(lfd, (struct sockaddr*)&cline_addr, &clien_len);
if(cfd == -1)
{
perror("accept error");
exit(1);
}
char ipbuf[64];
printf("cliient ip: %s, port: %d\n",
inet_ntop(AF_INET, &cline_addr.sin_addr.s_addr, ipbuf, sizeof(ipbuf)),
ntohs(cline_addr.sin_port));
while(1)
{
char buf[1024] = {0};
int len = read(cfd, buf, sizeof(buf));
if(len == -1)
{
perror("read error");
break;
}
else if(len > 0)
{
printf("read buf = %s\n", buf);
for(int i=0; i<len; ++i)
{
buf[i] = toupper(buf[i]);
}
printf(" -- toupper: %s\n", buf);
write(cfd, buf, strlen(buf)+1);
}
else if( len == 0 )
{
printf("client disconnect ...\n");
break;
}
}
close(lfd);
close(cfd);
return 0;
}
客户端
#include
#include
#include
#include
#include
#include
#include
#include
int main(int argc, const char* argv[])
{
if(argc <2){
printf("eg: ./a.out prot\n");
exit(1);
}
int port = atoi(argv[1]);
int fd = socket(AF_INET, SOCK_STREAM, 0);
if(fd == -1)
{
perror("socket error");
exit(1);
}
struct sockaddr_in serv_addr;
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(port);
inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr.s_addr);
int ret = connect(fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
if(ret == -1)
{
perror("connect error");
exit(1);
}
while(1)
{
char buf[1024];
printf("请输入要发送的字符串:\n");
fgets(buf, sizeof(buf), stdin);
write(fd, buf, strlen(buf)+1);
int len = read(fd, buf, sizeof(buf));
if(len == -1){
perror("read error");
exit(1);
}else if(len ==0){
printf("服务器端关闭了连接\n");
break;
}else{
printf("rec buf : \n");
printf("read buf = %s, len = %d\n", buf, len);
}
close(fd);
}
return 0;
}
测试
编译
$ gcc tcp_server.c -o server
$ gcc tcp_client.c -o client
启动服务端
$ ./server
cliient ip: 127.0.0.1, port: 50602
read buf = hello
-- toupper: HELLO
client disconnect ...
启动客户端
$ ./client 9999
请输入要发送的字符串:
hello
rec buf :
read buf = HELLO
, len = 7
请输入要发送的字符串:
world
read error: Bad file descriptor