Simple UDP server and client
2011-10-30 11:07
281 查看
server:
client:
////////////////////////////////////////////////////////// // UDPServer.cpp文件 #include <stdio.h> #include <winsock2.h> #pragma comment(lib, "WS2_32") // 链接到WS2_32.lib int main() { SOCKET mysock; WSADATA wsa; WSAStartup(MAKEWORD(2,2), &wsa); // 创建套节字 mysock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if(mysock == INVALID_SOCKET) { printf("Failed socket() \n"); return 0; } // 填充sockaddr_in结构 sockaddr_in sin; sin.sin_family = AF_INET; sin.sin_port = htons(4567); sin.sin_addr.S_un.S_addr = INADDR_ANY; // 绑定这个套节字到一个本地地址 if(bind(mysock, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR) { printf("Failed bind() \n"); return 0; } // 接收数据 char buff[1024]; sockaddr_in addr; int nLen = sizeof(addr); while(TRUE) { int nRecv = recvfrom(mysock, buff, 1024, 0, (sockaddr*)&addr, &nLen); if(nRecv > 0) { buff[nRecv] = '\0'; printf(" 接收到数据(%s):%s", ::inet_ntoa(addr.sin_addr), buff); } } closesocket(mysock); WSACleanup(); }
client:
////////////////////////////////////////////////////////// // UDPClient文件 #include <stdio.h> #include <winsock2.h> #pragma comment(lib, "ws2_32") int main() { WSADATA wsa; WSAStartup(MAKEWORD(2,2), &wsa); // 创建套节字 SOCKET s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if(s == INVALID_SOCKET) { printf("Failed socket() %d \n", WSAGetLastError()); return 0; } // 也可以在这里调用bind函数绑定一个本地地址 // 否则系统将会自动安排 // 填写远程地址信息 sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(4567); // 注意,这里要填写服务器程序所在机器的IP地址 // 如果你的计算机没有联网,直接使用127.0.0.1即可 addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); // 发送数据 char szText[] = " Here is the client \r\n"; sendto(s, szText, strlen(szText), 0, (sockaddr*)&addr, sizeof(addr)); closesocket(s); WSACleanup(); return 0; }
相关文章推荐
- Simple HTTP Server and Client in Python
- Simple HTTP Server and Client in Python
- Simple OAuth Client and Server Examples
- Simple client-server network using C++ and Windows Winsock
- UDP Server and Client under Linux
- Simple TCP Socket Client and Server Communication in C Under Linux
- Simple TcpClient and TcpServer in Java
- Linux UDP Server and Client Sample.Linux 下 UDP 服务和客户端程序示例
- ToyProgram UDP server and client with IOStream
- Python UDP Server and Client
- Simple HTTP Server and Client in Python
- Winsocket UDP Client and Server Examples
- WebSocket(一):Implement Simple Server and Client
- Simple HTTP Server and Client in Python
- Simple HTTP Server and Client in Python
- java nio mina 学习笔记1 Simple Server and Client
- Simple HTTP Server and Client in Python
- [转载]异步Socket服务器与客户端(An Asynchronous Socket Server and Client)
- A simple IOCP Server/Client Class
- Simple TCP/IP Echo Server & Client Application in C#