mark一下,以后的开发过程中可能会经常用到socket相关的东西,所以mark一下最基础的东西。
服务端代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
#include <stdio.h> #include <windows.h> #pragma comment(lib,"ws2_32.lib") void main() { //初始化套接字版本 WSAData wsaData; WSAStartup(MAKEWORD(2,2),&wsaData); //创建Socket SOCKET Socket_Server; Socket_Server = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if (Socket_Server == INVALID_SOCKET) { printf("Socket error"); return; } //初始化地址 sockaddr_in ClientAddr; ClientAddr.sin_family = AF_INET; ClientAddr.sin_port = htons(8000); ClientAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); //循环连接 while (true) { //连接 if (connect(Socket_Server,(LPSOCKADDR)&ClientAddr,sizeof(ClientAddr)) == SOCKET_ERROR) { printf("connect error/n"); Sleep(3000); continue; } printf("连接成功"); break; } //发送 if (send(Socket_Server,"上线了",sizeof("上线了"),0) == SOCKET_ERROR) { printf("send error"); return; } //关闭Socket closesocket(Socket_Server); WSACleanup(); } |
客户端代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
CreateThread(NULL,NULL,(LPTHREAD_START_ROUTINE)StartListen,NULL,NULL,NULL); DWORD StartListen(LPARAM *lparam) { WSAData wsaData; //初始化套接字版本 WSAStartup(MAKEWORD(2,2),&wsaData); SOCKET Socket_Client; //创建套接字 Socket_Client = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if (Socket_Client == INVALID_SOCKET) { printf("socket error"); return 0; } sockaddr_in sockaddr; //初始化地址信息 sockaddr.sin_family = AF_INET; sockaddr.sin_port = htons(8000); //8000端口 sockaddr.sin_addr.S_un.S_addr = INADDR_ANY; //表示所有可用的地址 //绑定套接字 if (bind(Socket_Client,(LPSOCKADDR)&sockaddr,sizeof(sockaddr)) == SOCKET_ERROR) { printf("bind error"); return 0; } //监听 if (listen(Socket_Client,5) == SOCKET_ERROR) { printf("listen error"); return 0; } SOCKET Socket_Server; //客户端 sockaddr_in remoteAddr; //服务端地址 int Addrlen = sizeof(remoteAddr); char revData[255]; while (true) { //接收连接 Socket_Server = accept(Socket_Client,(LPSOCKADDR)&remoteAddr,&Addrlen); if (Socket_Client == INVALID_SOCKET) { printf("accept error"); continue; } OutputDebugString("连接成功"); //接收数据 int ret = recv(Socket_Server,revData,sizeof(revData),0); if (ret > 0) { MessageBox(0,revData,0,0); } } closesocket(Socket_Server); //关闭socket WSACleanup(); } |
转载请注明:exchen's blog » 反向 Socket 连接