赞 | 1 |
VIP | 0 |
好人卡 | 0 |
积分 | 10 |
经验 | 0 |
最后登录 | 2022-7-26 |
在线时间 | 172 小时 |
Lv3.寻梦者
- 梦石
- 0
- 星屑
- 959
- 在线时间
- 172 小时
- 注册时间
- 2019-8-15
- 帖子
- 142
|
加入我们,或者,欢迎回来。
您需要 登录 才可以下载或查看,没有帐号?注册会员
x
/*
如果你发A,那服务器就会发B发C,服务器就会发D,类似于人工客服
当然,如果客户端发信息的话,那只会发出客户端发的字符串
摁exit服务器关闭线程
*/
- #include<bits/stdc++.h>
- #include "winsock.h"
- #pragma comment(lib,"ws2_32.lib")
- using namespace std;
- DWORD WINAPI threadpro(LPVOID pParam) {
- SOCKET hsock=(SOCKET)pParam;
- char buffer[1024];
- char sendBuffer[1024];
- if(hsock!=INVALID_SOCKET)
- cout<<"开始使用\n";
- for(;;) {
- int num=recv(hsock,buffer,1024,0);
- if(num>=0)
- cout<<"你:"<<buffer<<"\n";
- if(!strcmp(buffer,"A")) {
- memset(sendBuffer,0,1024);
- strcpy(sendBuffer,"B");
- int ires=send(hsock,sendBuffer,sizeof(sendBuffer),0);
- cout<<"服务器:"<<sendBuffer<<"\n";
- } else if(!strcmp(buffer,"C")) {
- memset(sendBuffer,0,1024);
- strcpy(sendBuffer,"D");
- int ires=send(hsock,sendBuffer,sizeof(sendBuffer),0);
- cout<<"服务器:"<<sendBuffer<<"\n";
- } else if(!strcmp(buffer,"exit")) {
- cout<<"关闭服务器\n";
- return 0;
- }
- }
- return 0;
- }
- int main(void) {
- SetConsoleTitle("服务端");
- WSADATA wsd;
- WSAStartup(MAKEWORD(2,2),&wsd);
- SOCKET m_SockServer;
- sockaddr_in serveraddr;
- sockaddr_in serveraddrfrom;
- SOCKET m_Server[20];
- serveraddr.sin_family=AF_INET;
- serveraddr.sin_port=htons(4600);
- serveraddr.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
- m_SockServer=socket(AF_INET,SOCK_STREAM,0);
- int i=bind(m_SockServer,(sockaddr*)&serveraddr,sizeof(serveraddr));
- cout<<i<<"\n";
- int iMaxConnect=10;
- int iConnect=0;
- int iLisRet;
- char buf[]="这是服务器\0";
- char WarnBuf[]="这是最大的连接数了\0";
- int len=sizeof(sockaddr);
- for(;;) {
- iLisRet=listen(m_SockServer,0);
- m_Server[iConnect]=accept(m_SockServer,(sockaddr*)&serveraddrfrom,&len);
- if(m_Server[iConnect]!=INVALID_SOCKET) {
- int ires=send(m_Server[iConnect],buf,sizeof(buf),0);
- cout<<"接收:"<<ires<<"\n";
- iConnect++;
- if(iConnect>iMaxConnect) {
- int ires=send(m_Server[iConnect],WarnBuf,sizeof(WarnBuf),0);
- } else {
- HANDLE m_Handle;
- DWORD nThreadld=0;
- m_Handle=(HANDLE)::CreateThread(NULL,0,threadpro,(LPVOID)m_Server[--iConnect],0,&nThreadld);
- }
- }
- WSACleanup();
- }
- }
复制代码 |
|