UDP简单实现
2012-09-19 17:16 龙成 阅读(247) 评论(1) 编辑 收藏 举报// UDPCLIENT.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> #include <WinSock2.h> #include <process.h> using namespace std; #pragma comment(lib,"WS2_32.lib") SOCKET s; SOCKADDR_IN servaddr; SOCKADDR_IN clientaddr; int len; char buf[100]; void rec(LPVOID p) { while(1) { len = sizeof(servaddr); memset(buf,0,100); if(recvfrom(s,buf,100,0,(sockaddr*)&servaddr,&len) == SOCKET_ERROR) { } else { if(strcmp(buf,"") != 0) cout << "服务器:" << buf << endl; } Sleep(100); } } void sed(LPVOID p) { while(1) { memset(buf,0,100); cin >> buf; if(sendto(s,buf,strlen(buf),0,(sockaddr*)&servaddr,sizeof(SOCKADDR_IN)) == 0) { cout << "sendto error!" << endl; } } } int _tmain(int argc, _TCHAR* argv[]) { WSADATA wsa; if(WSAStartup(MAKEWORD(2,2),&wsa) != 0) { cout << "wsastartup error!" << endl; return -1; } s = socket(AF_INET,SOCK_DGRAM,0); if(s == INVALID_SOCKET) { WSACleanup(); cout << "s error!" << endl; return -1; } servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); servaddr.sin_port = htons(5000); if(bind(s,(sockaddr*)&servaddr,sizeof(SOCKADDR_IN)) == SOCKET_ERROR) { cout << "bind error!" << endl; closesocket(s); WSACleanup(); return -1; } clientaddr.sin_family = AF_INET; clientaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); clientaddr.sin_port = htons(7000); _beginthread(sed,0,NULL); _beginthread(rec,0,NULL); while(1) { Sleep(1000); } // cout << buf << endl; closesocket(s); WSACleanup(); return 0; }
// UDPSEVER.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <WinSock2.h> #include <iostream> #include <process.h> using namespace std; #pragma comment(lib,"WS2_32.lib") SOCKET s; char buf[100]; SOCKADDR_IN clientaddr; SOCKADDR_IN servaddr; int len; void sed(LPVOID p) { while(1) { memset(buf,0,100); cin >> buf; if(sendto(s,buf,strlen(buf),0,(sockaddr*)&clientaddr,sizeof(SOCKADDR_IN)) == 0) { cout << "sendto error!" << endl; cout << GetLastError() << endl; } } } void rec(LPVOID p) { while(1) { len = sizeof(servaddr); memset(buf,0,100); if(recvfrom(s,buf,100,0,(sockaddr*)&clientaddr,&len) == SOCKET_ERROR) { } else { if(strcmp(buf,"") != 0) cout << "客户端:" << buf << endl; } Sleep(100); } } int _tmain(int argc, _TCHAR* argv[]) { WSADATA wsa; if(WSAStartup(MAKEWORD(2,2),&wsa) != 0) { cout << "wsastartup error!" << endl; return -1; } s = socket(AF_INET,SOCK_DGRAM,0); if(s == INVALID_SOCKET) { WSACleanup(); cout << "s error!" << endl; return -1; } servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); servaddr.sin_port = htons(7000); if(bind(s,(sockaddr*)&servaddr,sizeof(SOCKADDR_IN)) == SOCKET_ERROR) { cout << "bind error!" << endl; closesocket(s); WSACleanup(); return -1; } clientaddr.sin_family = AF_INET; clientaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); clientaddr.sin_port = htons((short)5000); _beginthread(sed,0,NULL); _beginthread(rec,0,NULL); // cout << "OK" << endl; while(1) { Sleep(1000); } closesocket(s); WSACleanup(); return 0; }