windows环境下C语言多线程实现网络编程,多人聊天室,
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
/***********************
服务器
************************/
#include "stdafx.h"
#include
#include
#include
#include "my_typedef.h"
#pragma comment(lib,"ws2_32.lib")
#define L_MAX (255)
#define C_MAX (100)
DWORD WINAPI ThreadProc( /* 线程函数*/ LPVOID lpParam
);
HANDLE tThread_Client[C_MAX] = {NULL};
LNode *pHead;
int main(int argc, char* argv[])
{
//初始化WSA
WORD sockVersion = MAKEWORD(2,2);
WSADATA wsaData;
if(WSAStartup(sockVersion, &wsaData)!=0)
{
return 0;
}
//创建套接字
SOCKET slisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(slisten == INV ALID_SOCKET)
{
printf("socket error !");
return 0;
}
//绑定IP和端口
sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(8888);
sin.sin_addr.S_un.S_addr = INADDR_ANY;
if(bind(slisten, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR)
{
printf("bind error !");
}
//开始监听
if(listen(slisten, C_MAX) == SOCKET_ERROR)
{
printf("listen error !");
return 0;
}
sockaddr_in remoteAddr;
int nAddrlen = sizeof(remoteAddr);
SOCKET sClient = NULL;
SOCKET Socket_Sclient = NULL;
/* 创建一个链表存放已经连接的客户端*/
pHead = (LNode*)malloc(sizeof(LNode));
pHead->pNext = NULL;
pHead->sClient = NULL;
/*循环等待客户端连接,并在连接后创建一个SOCKET和线程*/
while (true)
{
int i = 0;
printf("等待连接...\n");
sClient = accept(slisten, (SOCKADDR *)&remoteAddr, &nAddrlen);
if(sClient == INV ALID_SOCKET)
{
printf("accept error !");
continue;
}
else
{
Socket_Sclient = sClient;
add_Element(pHead,sClient);
tThread_Client[i] = CreateThread(NULL, 0, ThreadProc,(LPVOID)Socket_Sclient,
printf("接受到一个连接:%s \r\n", inet_ntoa(remoteAddr.sin_addr));
i++;
}
}
WSACleanup();
return 0;
}
DWORD WINAPI ThreadProc(
LPVOID lpParam
)
{
char Rev_Data[L_MAX] = {0};
char Send_Data[L_MAX] = {0};
//接收数据
while( strcmp(Rev_Data,"exit") != 0)
{
int ret = recv((SOCKET)lpParam, Rev_Data, L_MAX, 0);
LNode *p = pHead->pNext;
if(ret > 0)
{
Rev_Data[ret] = 0x00;
//发送数据
strcpy(Send_Data,Rev_Data);
if(!strcmp(Send_Data,"exit"))
{
printf("一个客户端已经断开连接!\n");
}
while (p != NULL )
{
if (p->sClient != (SOCKET)lpParam)
{
send(p->sClient, Send_Data, strlen(Send_Data), 0);
p = p->pNext;
}
else
{
p = p->pNext;
}
}