基於C 的區域網聊天系統伺服器端原始碼

2021-06-06 00:12:31 字數 2849 閱讀 9438

/*

* chat_server.h

**  created on: 2012-4-19

*      author: root

*/#ifndef chat_server_h_

#define chat_server_h_

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

using namespace std;

#include

#include

#define port 6000

typedef struct client_chat

chatinfo;

struct logic

;class chat_server

~chat_server()

int netinit();

int find_user();

int find(string& name);

static void* recv_msg(void* temp);

void accept();

void set_log(char* str);

};struct arg

;#endif /* chat_server_h_ */

/** chat_server.cpp

**  created on: 2012-4-19

*      author: root

*/#include "chat_server.h"

mapchat_server::clientinfo;

void chat_server::set_log(char* str)

int chat_server::netinit()

struct sockaddr_in sock_ss;

sock_ss.sin_family = pf_inet;

sock_ss.sin_port = htons(port);

sock_ss.sin_addr.s_addr = htonl(0);

socklen_t len = sizeof(sock_ss);

// int breuseaddr = 1;

//setsockopt(serverfd, sol_socket, so_reuseaddr, ( const int* )&breuseaddr, sizeof(int));

if( bind(serverfd,(struct sockaddr*)&sock_ss,len) < 0)

if( listen(serverfd,10) < 0 )

cout << "listen start..." << endl;

char* s = "listen start";

set_log(s);

return serverfd;

}int chat_server::find_user()

cout << "current zai xian ke hu: " << i << endl;

return 0;

}int chat_server::find(string& name)

}return -1;

}void* chat_server::recv_msg(void* temp)

close(sockfd);

pthread_exit(0);

}char* pbuf = buf;

memcpy(&cinfo.current_name,pbuf,sizeof(cinfo.current_name));

pbuf += sizeof(cinfo.current_name);

memcpy(&cinfo.group,pbuf,sizeof(cinfo.group));

pbuf += sizeof(cinfo.group);

memcpy(&cinfo.name,pbuf,sizeof(cinfo.name));

pbuf += sizeof(cinfo.name);

memcpy(&cinfo.msg,pbuf,sizeof(cinfo.msg));

pthread_mutex_lock(&(pthis->mutex));

clientinfo.insert(pair(sockfd,cinfo.current_name));

pthread_mutex_unlock(&(pthis->mutex));

if(!strcmp(cinfo.group,"y"))

}string tempname = cinfo.name;

int tmpfd = pthis->find(tempname);

if(tmpfd < 0)

else

}return null;

}void chat_server::accept()

arg* arg = new arg();

arg->fd = fd;

arg->pthis = this;

pthread_t recv_pid = -1;

pthread_create(&recv_pid,null,recv_msg,(void*)arg);}}

/** chat_server_main.cpp

**  created on: 2012-4-19

*      author: root

*/#include "chat_server.h"

int main(int argc,char** argv)

C Socket編寫區域網聊天室(伺服器端)

需要的引用包括 using system.net using system.net.sockets using system.threading 首先要建立socket,將其繫結到本機的ip位址,給它乙個埠號。然後開始監聽 什麼是ip位址和埠號?每乙個計算機都有乙個ip位址。通過ip位址可以在網路中...

基於C 的區域網聊天系統客戶

chat client.h created on 2012 4 19 author root ifndef chat client h define chat client h include include include include include include include using...

基於python的簡易區域網聊天工具

threading 多執行緒模組,實現同時接收,同時傳送 本地機器兩個命令視窗不同埠號執行,實際使用可在區域網內電腦執行 接受資訊函式 def rec upd while true 接收訊息,最多為1024位元組 data upd.recvfrom 1024 data為乙個元組,info為資訊內容,...