/* * Author: Leng_que * Date: 2009年11月14日 * E-mail: leng_que@yahoo.com.cn * Description: 服务端 —— TCP编程 */ #include <stdio.h> #include <winsock2.h> #pragma comment(lib, "ws2_32.lib") int main(void) { char buf[32]={0}; WSADATA wsa={0}; SOCKET s=0; struct sockaddr_in s_ip={0}; s_ip.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); s_ip.sin_family = AF_INET; s_ip.sin_port = htons(8888); struct sockaddr_in client_addr={0}; int addrlen = sizeof(struct sockaddr); SOCKET client_s=0; //socket接收超时设置 int nTimeout = 3000; int ret = WSAStartup(MAKEWORD(2,0), &wsa); if ( !ret ) { s = socket(AF_INET, SOCK_STREAM, 0); if ( s != INVALID_SOCKET ) { setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (const char*)&nTimeout, sizeof(nTimeout)); if ( !bind(s, (const sockaddr*)&s_ip, sizeof(struct sockaddr)) ) { if ( !listen(s, 8) ) { printf("正在监听本机8888端口……/r/n"); while(true) { client_s = accept(s, (struct sockaddr*)&client_addr, &addrlen); if ( client_s != INVALID_SOCKET ) { printf("成功接受来自%s的连接。/r/n/r/n", inet_ntoa(client_addr.sin_addr)); int len=0; strcpy(buf, "我是服务器端"); len = send(client_s, (const char*)&buf, strlen(buf), 0); printf("共发出%dbyte的数据包,内容为:%s/r/n", len,buf); memset(buf, 0, sizeof(buf)); len = recv(client_s, buf, sizeof(buf), 0); printf("接收到%dbyte的数据包,内容为:%s/r/n", len,buf); break; } else { break; } } } } } } if ( client_s!=NULL ) { closesocket(client_s); } if ( s!=NULL ) { closesocket(s); } if ( !ret ) { WSACleanup(); } return 0; } /* * Author: Leng_que * Date: 2009年11月14日 * E-mail: leng_que@yahoo.com.cn * Description: 客户端 —— TCP编程 */ #include <stdio.h> #include <winsock2.h> #pragma comment(lib, "ws2_32.lib") int main(void) { char buf[32]={0}; WSADATA wsa={0}; SOCKET s=0; struct sockaddr_in s_ip={0}; s_ip.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); s_ip.sin_family = AF_INET; s_ip.sin_port = htons(8888); //socket接收超时设置 int nTimeout = 3000; int ret = WSAStartup(MAKEWORD(2,0), &wsa); if ( !ret ) { s = socket(AF_INET, SOCK_STREAM, 0); if ( s != INVALID_SOCKET ) { setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (const char*)&nTimeout, sizeof(nTimeout)); printf("正在连接服务端……/r/n"); if ( !connect(s, (struct sockaddr *)&s_ip, sizeof(struct sockaddr)) ) { int len=0; printf("/r/n"); memset(buf, 0, sizeof(buf)); len = recv(s, buf, sizeof(buf), 0); printf("接收到%dbyte的数据包,内容为:%s/r/n", len,buf); strcpy(buf, "我是客户端"); len = send(s, buf, strlen(buf), 0); printf("共发出%dbyte的数据包,内容为:%s/r/n", len,buf); } else { printf("连接超时!"); } } } if ( s!=NULL ) { closesocket(s); } if ( !ret ) { WSACleanup(); } return 0; }