Winsock入门,socket编程,网络
客户端代码:
#include <stdio.h> #include <string.h> #include <winsock2.h> #pragma comment(lib,"Ws2_32.lib") #define BUFFER_SIZE 50 /*客户端代码 by ZZR http://blog.csdn.net/zhengzhiren */ int main() { int err; SOCKET sClient; char ip[20]; /*IP地址*/ char buf[BUFFER_SIZE]; /*数据发送缓冲区*/ int port; /*端口*/ WSADATA wsaD; struct sockaddr_in servaddr; /*存放服务器端网络地址的结构*/ printf("Please input target IP and Port(eg:127.0.0.1 5555):/n"); scanf("%s%hu",ip,&port); memset(&servaddr,0,sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = inet_addr(ip); servaddr.sin_port = htons(port); /*Winsock初始化*/ err = WSAStartup(MAKEWORD(1,1),&wsaD); /*创建Socket*/ if((sClient = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)) == SOCKET_ERROR){ err = WSAGetLastError(); printf("Create socket error %d",err); return -1; } /*连接到服务器*/ if(connect(sClient,(struct sockaddr *) &servaddr,sizeof(servaddr)) == SOCKET_ERROR){ err = WSAGetLastError(); printf("Failed to connect to server!%d/n",err); return -1; } printf("Connected to server %s/n",inet_ntoa(servaddr.sin_addr)); while(1) { gets(buf); if (strcmp(buf,"quit")==0 || strcmp(buf,"exit")==0) break; send(sClient,buf,strlen(buf)+1,0) ;/*发送数据*/ } closesocket(sClient); WSACleanup(); }
服务端代码:
#include <stdio.h> #include <winsock2.h> #pragma comment(lib,"Ws2_32.lib") //#pragma comment(linker, "/SUBSYSTEM:CONSOLE") #define BUFFER_SIZE 500 /*服务端代码 by ZZR http://blog.csdn.net/zhengzhiren */ int main() { int err; int len; SOCKET sListen; /*监听套接字*/ SOCKET sConnect; /*用于建立连接的套接字*/ WSADATA wsaD; struct sockaddr_in my_addr; u_short port; /*监听端口*/ char buf[BUFFER_SIZE]; struct sockaddr_in addr; /*客户机的网络地址*/ int addrlen; /*地址长度*/ printf("Please input Port:/n"); scanf("%hu",&port); err = WSAStartup(MAKEWORD(1,1),&wsaD); /* 初始化Winsock */ if((sListen = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)) == SOCKET_ERROR){ /* 创建套接字s */ err = WSAGetLastError(); printf("%d socket error!",err); return -1; } memset(&my_addr,0,sizeof(my_addr)); /* 清空sockaddr结构 */ my_addr.sin_family = AF_INET; my_addr.sin_port = htons(port); my_addr.sin_addr.s_addr = htonl(INADDR_ANY); if(bind(sListen,(struct sockaddr *) &my_addr,sizeof(my_addr)) == SOCKET_ERROR) /* 绑定 */ { err = WSAGetLastError(); printf("Error:%d Failed to bind!/n",err); return -1; } if(listen(sListen,5) == SOCKET_ERROR) /* 启动监听 */ { err = WSAGetLastError(); printf("Error:%d Failed to listen!/n",err); return -1; } printf("Listening on port %d/n",ntohs(my_addr.sin_port)); addrlen = sizeof(addr); if((sConnect = accept(sListen,(struct sockaddr *) &addr,&addrlen)) != INVALID_SOCKET) printf("%s has connected to this server./n",inet_ntoa(addr.sin_addr)); while(1){ memset(buf,0,sizeof(buf)); len = recv(sConnect,buf,sizeof(buf),0); /*接收数据*/ if (len > 0) { printf("%s",buf); } else if (len==0) { closesocket(sConnect); break; } } WSACleanup(); return 0; }