/*
tcp聊天室 客戶端
*/#include
#include
#include
#include
#include
#include
#include
#include
#include
//一些準備工作
char* ip = "172.30.11.104"; 本機位址,回送位址,用於網路軟體測試 或本機通訊
short port = 10222; // 埠
typedef struct sockaddr sa; //用做型別轉換
int sockfd= 0;
char name[20] = {};
//1 啟動客戶端,連線伺服器
void init()
printf("客戶端啟動成功\n");
}//2 開始通訊
void start()
;scanf("%s",buf);//讀取客戶的輸入
char msg[200] = {};
sprintf(msg,"%s 說:%s",name,buf);
send(sockfd,msg,strlen(msg),0);}}
//執行緒函式 ,用來接收訊息
void* recv_thread(void* p)
;if(recv(sockfd,buf,sizeof(buf),0)<=0)
printf("%s\n",buf);
}void sig_close(int signo)
int main()
/*tcp聊天室伺服器
*/#include
#include
#include
#include
#include
#include
#include
#include
#include
//一些準備工作
char* ip = "172.30.11.104"; 本機位址,回送位址,用於網路軟體測試 或本機通訊
short port = 10222; // 埠
typedef struct sockaddr sa; //用做型別轉換
struct client
;struct client c[100] = ;//記錄客戶端的結構體陣列 最多記錄了100個
int size = 0; //記錄客戶端的個數,也可以用來遍歷客戶端結構體
int sockfd = 0; //伺服器的sockt
//1 初始化伺服器的網路,建立socket
void init()
printf("繫結成功\n");
if(listen(sockfd,100) == -1)
printf("設定監聽成功\n");
//等待客戶端連線到另乙個函式中
printf("初始化伺服器成功\n");}/*
輔助函式,用來分發訊息
*/void sendmsgtoall(char* msg)
;if(recv(fd,name,sizeof(name),0)>0) //接收暱稱
size++;
//先**一條訊息,表示歡迎 也可以通知其他客戶端有人連線了 進入聊天室
char tishi[100];
sprintf(tishi,"熱烈歡迎%s登陸聊天室。。",name);
//**訊息
sendmsgtoall(tishi);
//通訊部分,收發訊息
while(1)
;if(recv(fd,buf,sizeof(buf),0) == 0)
;for(i= 0;ifd=%d\n",fd);
char msg[100] = {};
sprintf(msg,"歡送 %s 離開聊天室,再見\n",name);
sendmsgtoall(msg);
close(fd);
return ; //客戶端退出 結束執行緒
}sendmsgtoall(buf); //成功接收到訊息,就直接所有的客戶端}}
//等待客戶端連線,啟動伺服器服務
void service()
//如果客戶成功連線
//開啟執行緒,為該客戶端進行服務
printf("fd =%d\n",fd);
pthread_t pid;
pthread_create(&pid,0,service_thread,&fd);}}
void sig_close(int signo)
int main()
簡單聊天室
include include include include include include include include include include pthread t thread 2 void send msg void ip msg if connect sockfd,struct ...
Linux UDP簡單聊天室
伺服器端 include include include include include include include include int sockfd 0 建立結構體用來存放客戶端資訊 typedef struct node node t node t link head node t h ...
go 簡單聊天室
package main import fmt net strings time 建立使用者結構體型別 type cline struct var onlinemap map string cline 建立全域性 channel 傳遞使用者訊息 var message make chan strin...