69,336
社区成员
发帖
与我相关
我的任务
分享
void startSocket()
{
WSADATA wsaData;
int recvbytes;
int sockfd,client_fd;
struct sockaddr_in my_server;
struct sockaddr_in remote_addr;
unsigned char buf[MAXDATASIZE];
WSAStartup(MAKEWORD(2,0),&wsaData);
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd<0)
{
ShowError();
}
my_server.sin_family=AF_INET;
my_server.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
my_server.sin_port=htons(5000);//htons(5000);
if (bind(sockfd, (struct sockaddr *)&my_server, sizeof(struct sockaddr)) == -1) {
ShowError();
}
if (listen(sockfd, BACKLOG) == -1) {
ShowError();
}
while(1) {
int sin_size = sizeof(struct sockaddr_in);
if ((client_fd = accept(sockfd, (struct sockaddr *)&remote_addr, &sin_size)) == -1) {
perror("accept Error");
continue;
}
printf("received a connection from %s\n", inet_ntoa(remote_addr.sin_addr)); //inet_ntoa(将网络二进制的数字转换成网络地址)
if (!fork()) {
unsigned char *msg="abc";
if ((recvbytes=recv(client_fd, buf, MAXDATASIZE, 0)) ==-1) {
perror("recv Error!");
exit(1);
}
buf[recvbytes] = '\0';
printf("Received: %s\n",buf);
//给客户端发送数据
if (send(client_fd, msg,strlen(msg), 0) == -1) {
perror("send Error");
/* 这个通讯已经结束 */
close(client_fd);
exit(0);
}
}
}
}
BOOL CreateSocketInformation(SOCKET s);
void FreeSocketInformation(DWORD Index);
void SendData(LPSOCKET_INFORMATION SocketInfo,int i);
DWORD TotalSockets = 0;
LPSOCKET_INFORMATION SocketArray[FD_SETSIZE];
void main(void)
{
SOCKET ListenSocket;
SOCKET AcceptSocket;
SOCKADDR_IN InternetAddr;
WSADATA wsaData;
INT Ret;
FD_SET WriteSet;
FD_SET ReadSet;
DWORD i;
DWORD Total;
ULONG NonBlock;
DWORD Flags;
DWORD RecvBytes;
if ((Ret = WSAStartup(0x0202,&wsaData)) != 0)
{
printf("WSAStartup() failed with error %d\n", Ret);
WSACleanup();
return;
}
// Prepare a socket to listen for connections.
if ((ListenSocket = WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0,
WSA_FLAG_OVERLAPPED)) == INVALID_SOCKET)
{
printf("WSASocket() failed with error %d\n", WSAGetLastError());
return;
}
InternetAddr.sin_family = AF_INET;
InternetAddr.sin_addr.s_addr = htonl(INADDR_ANY);
InternetAddr.sin_port = htons(PORT);
if (bind(ListenSocket, (PSOCKADDR) &InternetAddr, sizeof(InternetAddr))
== SOCKET_ERROR)
{
printf("bind() failed with error %d\n", WSAGetLastError());
return;
}
if (listen(ListenSocket, 5))
{
printf("listen() failed with error %d\n", WSAGetLastError());
return;
}
// Change the socket mode on the listening socket from blocking to
// non-block so the application will not block waiting for requests.
NonBlock = 1;
if (ioctlsocket(ListenSocket, FIONBIO, &NonBlock) == SOCKET_ERROR)
{
printf("ioctlsocket() failed with error %d\n", WSAGetLastError());
return;
}
while(TRUE)
{
// Prepare the Read and Write socket sets for network I/O notification.
FD_ZERO(&ReadSet);
FD_ZERO(&WriteSet);
// Always look for connection attempts.
FD_SET(ListenSocket, &ReadSet);
// Set Read and Write notification for each socket based on the
// current state the buffer. If there is data remaining in the
// buffer then set the Write set otherwise the Read set.
for (i = 0; i < TotalSockets; i++)
FD_SET(SocketArray[i]->Socket, &ReadSet);
if ((Total = select(0, &ReadSet, NULL, NULL, NULL)) == SOCKET_ERROR)
{
printf("select() returned with error %d\n", WSAGetLastError());
return;
}
// Check for arriving connections on the listening socket.
if (FD_ISSET(ListenSocket, &ReadSet))
{
Total--;
if ((AcceptSocket = accept(ListenSocket, NULL, NULL)) != INVALID_SOCKET)
{
// Set the accepted socket to non-blocking mode so the server will
// not get caught in a blocked condition on WSASends
NonBlock = 1;
if (ioctlsocket(AcceptSocket, FIONBIO, &NonBlock) == SOCKET_ERROR)
{
printf("ioctlsocket() failed with error %d\n", WSAGetLastError());
return;
}
if (CreateSocketInformation(AcceptSocket) == FALSE)
return;
}
else
{
if (WSAGetLastError() != WSAEWOULDBLOCK)
{
printf("accept() failed with error %d\n", WSAGetLastError());
return;
}
}
}
// Check each socket for Read and Write notification until the number
// of sockets in Total is satisfied.
for (i = 0; Total > 0 && i < TotalSockets; i++)
{
LPSOCKET_INFORMATION SocketInfo = SocketArray[i];
// If the ReadSet is marked for this socket then this means data
// is available to be read on the socket.
if (FD_ISSET(SocketInfo->Socket, &ReadSet))
{
Total--;
SocketInfo->DataBuf.buf = SocketInfo->Buffer;
SocketInfo->DataBuf.len = DATA_BUFSIZE;
Flags = 0;
if (WSARecv(SocketInfo->Socket, &(SocketInfo->DataBuf), 1, &RecvBytes,
&Flags, NULL, NULL) == SOCKET_ERROR)
{
if (WSAGetLastError() != WSAEWOULDBLOCK)
{
printf("WSARecv() failed with error %d\n", WSAGetLastError());
FreeSocketInformation(i);
}
continue;
}
else
{
SocketInfo->BytesRECV = RecvBytes;
SocketInfo->DataBuf.len = RecvBytes;
//处理接收数据
// If zero bytes are received, this indicates the peer closed the
// connection.
if (RecvBytes == 0)
{
FreeSocketInformation(i);
continue;
}
}
}
}
}
}
BOOL CreateSocketInformation(SOCKET s)
{
LPSOCKET_INFORMATION SI;
printf("Accepted socket number %d\n", s);
if ((SI = (LPSOCKET_INFORMATION) GlobalAlloc(GPTR,
sizeof(SOCKET_INFORMATION))) == NULL)
{
printf("GlobalAlloc() failed with error %d\n", GetLastError());
return FALSE;
}
// Prepare SocketInfo structure for use.
SI->Socket = s;
SI->BytesSEND = 0;
SI->BytesRECV = 0;
SocketArray[TotalSockets] = SI;
TotalSockets++;
return(TRUE);
}
void FreeSocketInformation(DWORD Index)
{
LPSOCKET_INFORMATION SI = SocketArray[Index];
DWORD i;
closesocket(SI->Socket);
printf("Closing socket number %d\n", SI->Socket);
GlobalFree(SI);
// Squash the socket array
for (i = Index; i < TotalSockets; i++)
{
SocketArray[i] = SocketArray[i + 1];
}
TotalSockets--;
}
void SendData(LPSOCKET_INFORMATION SocketInfo,int i)
{
DWORD SendBytes;
if (WSASend(SocketInfo->Socket, &(SocketInfo->DataBuf), 1, &SendBytes, 0,
NULL, NULL) == SOCKET_ERROR)
{
if (WSAGetLastError() != WSAEWOULDBLOCK)
{
printf("WSASend() failed with error %d\n", WSAGetLastError());
FreeSocketInformation(i);
}
}
}