作者:百变靓丽 | 来源:互联网 | 2023-07-26 15:33
1. Linux server端代码(test.cpp)
#ifdef WIN32
#include
#else
#include
#include
#include
#include
#include
#endif
#include
int main(int argc, char *argv[]){
#ifdef WIN32
WSADATA ws;
WSAStartup(MAKEWORD(2,2), &ws);
#endif
int sock = socket(AF_INET,SOCK_STREAM,0);
if(sock == -1){
printf("create sock error!\n");
return -1;
}
unsigned short port = 8080;
if(argc > 1){
port = atoi(argv[1]);
}
sockaddr_in saddr;
saddr.sin_family = AF_INET;
saddr.sin_port = htons(port);
saddr.sin_addr.s_addr = 0;
if(bind(sock, (sockaddr*)&saddr, sizeof(saddr))!=0){
printf("OS bind socks to this port %d failed\n", port);
return -2;
}
printf("OS bind this port %d to sockets successfully!", port);
listen(sock, 10);
getchar();
return 0;
}
2. 分析
客户端模拟通过telnet成功连接!如下图,
但是,客户端还是无法向服务器端发送数据!下文讲述如何用accept()函数解决这个问题。
参考
http://blog.csdn.net/dengjin20104042056/article/details/52357452