注意:博主用的visual studio 2015,在windows调试程序需要链接ws2_32.lib库,才能正常运行程序。
打开项目的“Property”->"Linker"->"Input"->"Additional Dependencies",或者你也可以通过快捷键Alt+F7打开Property页面. 不知如何操作,可以看 http://blog.csdn.net/qq_16542775/article/details/51203465.
这里只贴出代码(操作方法和(基于TCP的服务器端/客户端方法相同!)):
uecho_server_win.c
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<WinSock2.h> #define BUF_SIZE 30 void ErrorHandling(char *message); int main(int argc, char *argv[]) { WSADATA wsaData; SOCKET servSock; char message[BUF_SIZE]; int strLen; int clntAdrSz; SOCKADDR_IN servAdr, clntAdr; if (argc != 2) { printf("Usage : %s<port>\n", argv[0]); exit(1); } if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) ErrorHandling("WSAStartup() error!"); servSock = socket(PF_INET, SOCK_DGRAM, 0); if (servSock == INVALID_SOCKET) ErrorHandling("UDP socket creation error!"); memset(&servAdr, 0, sizeof(servAdr)); servAdr.sin_family = AF_INET; servAdr.sin_addr.S_un.S_addr = htonl(INADDR_ANY); servAdr.sin_port = htons(atoi(argv[1])); if (bind(servSock, (SOCKADDR*)&servAdr, sizeof(servAdr)) == SOCKET_ERROR) ErrorHandling("bind() error!"); while (1) { clntAdrSz = sizeof(clntAdr); strLen = recvfrom(servSock, message, BUF_SIZE, 0, (SOCKADDR*)&clntAdr,&clntAdrSz); sendto(servSock, message, strLen, 0, (SOCKADDR*)&clntAdr, sizeof(clntAdr)); } close(servSock); WSACleanup(); return 0; } void ErrorHandling(char *message) { fputs(message, stderr); fputc('\n', stderr); exit(1); }
uecho_client_win.c
#define _WINSOCK_DEPRECATED_NO_WARNINGS #include<stdio.h> #include<stdlib.h> #include<string.h> #include<WinSock2.h> #define BUF_SIZE 30 void ErrorHandling(char *message); int main(int argc, char *argv[]) { WSADATA wsaData; SOCKET sock; char message[BUF_SIZE]; int strLen; SOCKADDR_IN servAdr; if (argc != 3) { printf("Usage: %s <IP><port>\n", argv[0]); exit(1); } if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) ErrorHandling("WSAStartup() error!"); sock = socket(PF_INET, SOCK_DGRAM, 0); if (sock == INVALID_SOCKET) ErrorHandling("socket() error!"); memset(&servAdr, 0, sizeof(servAdr)); servAdr.sin_family = AF_INET; servAdr.sin_addr.S_un.S_addr = inet_addr(argv[1]); servAdr.sin_port = htons(atoi(argv[2])); connect(sock, (SOCKADDR*)&servAdr, sizeof(servAdr)); while (1) { fputs("Insert message(q to quit): ", stdout); fgets(message, sizeof(message), stdin); if (!strcmp(message, "q\n") || !strcmp(message, "Q\n")) break; send(sock, message,strlen(message), 0); strLen = recv(sock, message, sizeof(message) - 1, 0); message[strLen] = 0; printf("Message from server: %s", message); } closesocket(sock); WSACleanup(); return 0; } void ErrorHandling(char *message) { fputs(message, stderr); fputc('\n', stderr); }