想要实现的功能:在服务器端有一个控制台程序(或者Windows服务),与多个客户端程序通讯,其中主线程有一个socket绑定在一个固定端口上,负责监听客户端的Socket信息。每当启动一个客户端程序,客户端发送来一个socket连接请求,server端就新开启一个线程,并在其中创建一个socket与该客户端的socket通讯,直到客户端程序关闭,结束该线程。主线程中的socket在应用程序退出时关闭。
这里是Server端代码的简单示意,展示了如何创建多线程的Socket Server。
#include "StdAfx.h"
#include <stdio.h>
DWORD WINAPI AnswerThread(LPVOID lparam)
{
SOCKET ClientSocket=(SOCKET)(LPVOID)lparam;
int bytesRecv;
char sendbuf[32]="";
char recvbuf[32]="";
while(1)
{
bytesRecv=SOCKET_ERROR;
for(int i=0;i<(int)strlen(recvbuf);i++)
{ recvbuf[i]='\0'; }
while(bytesRecv==SOCKET_ERROR)
{ //Receiving Data
bytesRecv=recv(ClientSocket,recvbuf,32,0);
}
//Write your processing code here
send(ClientSocket,recvbuf,strlen(recvbuf),0);
printf("%s\n",recvbuf);
}
return 0;
}
int main(int argc,char* argv[])
{
//initialize Winsock
WSADATA wsaData;
int iRet=WSAStartup(MAKEWORD(2,2),&wsaData);
if(iRet!=NO_ERROR)
printf("Error at WSAStartup()\n");
//create a socket
SOCKET m_socket;
m_socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(m_socket==INVALID_SOCKET)
{
printf("Error at socket():%ld\n",WSAGetLastError());
WSACleanup();
return 0;
}
//bind a socket
sockaddr_in service;
service.sin_family=AF_INET;
service.sin_addr.s_addr=inet_addr("172.16.3.250");
service.sin_port=htons(2501);
if(bind(m_socket,(SOCKADDR*)&service,sizeof(service))==SOCKET_ERROR)
{
printf("bind() failed.\n");
closesocket(m_socket);
return 0;
}
else
printf("bind OK.\n");
//listen on a socket
if(listen(m_socket,20)==SOCKET_ERROR)
printf("Error listening on socket.\n");
else
printf("listening ok.\n");
//accept a connection
SOCKET AcceptSocket;
printf("Waiting for a client to connect...\n");
while(1)
{
AcceptSocket=SOCKET_ERROR;
while(AcceptSocket==SOCKET_ERROR)
{
AcceptSocket=accept(m_socket,NULL,NULL);
}
printf("Client Connected.\n");
DWORD dwThreadId;
HANDLE hThread;
hThread=CreateThread(NULL,NULL, AnswerThread,
(LPVOID)AcceptSocket,0,&dwThreadId);
if(hThread==NULL)
{
printf("CreatThread AnswerThread() failed.\n");
}
else
{
printf("CreateThread OK.\n");
}
}
return 0;
}
Socket的客户端程序就很简单了,可以使用VB拖一个WinSock控件到Form中,然后连接服务器的Socket并发送数据就行了。
本文地址:http://com.8s8s.com/it/it744.htm