//禁止数据对齐,节约空间,加快网络传输速度 // #pragma pack(push,1) struct MsgStruct { char buffer[512]; char name[10]; char time[9]; }; //恢复原来的对齐设置 #pragma pack(pop)
#include <stdio.h> #include <iostream> #include <process.h> #include <time.h> #include "winsock2.h" #include "SendStruct.h" unsigned __stdcall SendThread(void* socket); void main() { // 检查 Winsock 版本号,WSAData为WSADATA结构对象 WSADATA wsaData; int iResult = WSAStartup(MAKEWORD(2,2), &wsaData); if (iResult != NO_ERROR) printf("Error at WSAStartup()/n"); //创建套接字 SOCKET ConnectSocket; ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (ConnectSocket == INVALID_SOCKET) { printf("Error at socket(): %ld/n", WSAGetLastError()); WSACleanup(); return; } //填写远程地址信息 sockaddr_in clientService; clientService.sin_family = AF_INET; clientService.sin_port = htons( 27015 ); //填写服务器程序所在的机器的IP地址 //clientService.sin_addr.s_addr = inet_addr( "192.168.21.76" ); clientService.sin_addr.s_addr = inet_addr( "127.0.0.1" ); /*char ipArr[20]; printf("input you want to connect IP:"); scanf("%s",ipArr); clientService.sin_addr.S_un.S_addr = inet_addr(ipArr);*/ //连接服务器端 if ( connect( ConnectSocket, (SOCKADDR*) &clientService, sizeof(clientService) ) == SOCKET_ERROR) { printf( "Failed to connect./n" ); WSACleanup(); return; } //创建句柄 HANDLE hCliThread; unsigned threadID; //产生线程 3.线程创建后调用的函数,4.该函数的参数,6.线程ID 方便对线程进行管理 hCliThread = (HANDLE)_beginthreadex(NULL,0,SendThread,(void *)ConnectSocket,0,&threadID); int bytesRecv = 0; //创建一个接收的结构体,用于接收并解析 struct MsgStruct *RecvBuf = (struct MsgStruct *)malloc(sizeof(struct MsgStruct)); for(;;)//recevice data from server { //接收连接上来的服务端,在客户器端创建一个socket为ConnectSocket,服务端发送过来的相关信息放在(char*)RecvBuf中 bytesRecv = recv(ConnectSocket,(char*)RecvBuf,sizeof(struct MsgStruct),0); //当服务端退出时跳出当前循环 if(bytesRecv <= 0 || bytesRecv == WSAECONNRESET) { printf("connect failed!/n"); printf("server was cut!please quit!"); break; } printf("/n%s ",RecvBuf->name); printf("%s /n",RecvBuf->time); printf("%s /n",RecvBuf->buffer); memset(RecvBuf,0,sizeof(struct MsgStruct));//清空struct也行 } free(RecvBuf); WSACleanup(); return; } unsigned __stdcall SendThread(void *socket)//send data to otherclient and server { struct MsgStruct *SendBuf = (struct MsgStruct *)malloc (sizeof(struct MsgStruct)); char namebuf[10] = ""; memset(namebuf,0,strlen(namebuf)); printf("欢迎进入进宇YY聊天室,这里可以群聊!测试版 /n"); printf("your name: "); scanf("%s",namebuf); //先发送一个名字过去,让服务端先接受一个信息 send((SOCKET)socket,namebuf,strlen(namebuf),0); //send((SOCKET)socket,SendBuf->name,strlen(SendBuf->name),0);//怎么会出现乱码呢? for(;;) { //循环发送信息 strcpy(SendBuf->name , namebuf); printf("please input:"); if( scanf("%s",SendBuf->buffer) <= 0) { printf("please input again!/n"); scanf("%s",SendBuf->buffer); } _strtime(SendBuf->time); if((send((SOCKET)socket,(char*)SendBuf,sizeof(struct MsgStruct),0)) < 0 ) { printf("send failed!wait for a moment/n"); } //将SendBuf清空 memset(SendBuf,0,sizeof(struct MsgStruct)); } //结束线程 _endthreadex( 0 ); return 0; }