S
//#ifndef _GOQOMESSAGE_H_
//#define _GOQOMESSAGE_H_
//#endif
#include"goqomessage.h"
#include<winsock2.h>
#include<stdio.h>
#include<windows.h>
#pragma comment(lib,"WS2_32.lib")
//线程处理函数
DWORD WINAPI ThreadFunc(LPVOID client)
{
SOCKET cli=(SOCKET)client;
char buffer[1044];
GoQoMessage mes;
memset(buffer,0,sizeof(buffer));
// 对MES进行填充
mes.SourceClientId=123456;
for (int i=0; i<1023; ++i)
{
mes.MessageContent[i] = 'a';
}
mes.MessageContent[1023]='/0';
memcpy(buffer,&mes,sizeof(mes));
int isend;
for (;;)
{
isend=send(cli,buffer,sizeof(buffer),0);
if(isend>0)
{
printf("send data to %d success/n",cli);
Sleep(2000);
}
else
{
break;
}
}
closesocket(cli);
return true;
}
//程序开始
int main(int argc, char* argv[])
{
WSADATA wsaData;
WORD sockVersion=MAKEWORD(2,0);
WSAStartup(sockVersion,&wsaData);
SOCKET s=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(s==INVALID_SOCKET)
{
printf(" Failed socket()/n");
WSACleanup();
return 0;
}
sockaddr_in sin;
sin.sin_family=AF_INET;
sin.sin_port=htons(8888);
sin.sin_addr.S_un.S_addr=INADDR_ANY;
if(bind(s,(LPSOCKADDR)&sin,sizeof(sin))==SOCKET_ERROR)
{
printf(" Failed bind()/n");
WSACleanup();
return 0;
}
if(listen(s,100)==SOCKET_ERROR)
{
printf(" Failed listen()/n");
WSACleanup();
return 0;
}
sockaddr_in remoteAddr;
int nAddrLen=sizeof(remoteAddr);
SOCKET client;
char szText[]="Hello World!";
printf("sever start sucess: /n");
while(TRUE)
{
client=accept(s,(SOCKADDR*)&remoteAddr,&nAddrLen);
if(client==INVALID_SOCKET)
{
printf(" Failed accept()/n");
continue;
}
printf("接收到一个连接:%s/n",inet_ntoa(remoteAddr.sin_addr));
HANDLE hThread = CreateThread(NULL,0,ThreadFunc, (void*)client,0,NULL);
if (hThread == NULL)
{
printf("creat thread faile:/n");
continue;
}
//send(client,szText,strlen(szText),0);
//closesocket(client);
}
closesocket(s);
WSACleanup();
return 0;
}
c
#include "goqomessage.h"
#include<winsock2.h>
#include<stdio.h>
#include<windows.h>
#pragma comment(lib,"WS2_32.lib")
int main(int argc, char* argv[])
{
WSADATA wsaData;
WORD sockVersion=MAKEWORD(2,0);
WSAStartup(sockVersion,&wsaData);
SOCKET s=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(s==INVALID_SOCKET)
{
printf(" Failed socket()/n");
WSACleanup();
return 0;
}
sockaddr_in servAddr;
servAddr.sin_family=AF_INET;
servAddr.sin_port=htons(8888);
servAddr.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
if(connect(s,(sockaddr*)&servAddr,sizeof(servAddr))==-1)
{
printf(" Failed connect()/n");
WSACleanup();
return 0;
}
for(;;)
{
char buffer[1044];
memset(buffer,0,sizeof(buffer));
int nRecv=recv(s,buffer,sizeof(buffer),0);
if(nRecv>0)
{
buffer[nRecv]='/0';
GoQoMessage mes;
memcpy(&mes,buffer,sizeof(buffer));
printf("已经接收到来处用户%d数据:/n%s/n",mes.SourceClientId,mes.MessageContent);
Sleep(2000);
}
else
{
break;
}
}
closesocket(s);
WSACleanup();
return 0;
}