當前位置:首頁 » 編程軟體 » socket編程聊天室

socket編程聊天室

發布時間: 2023-06-26 06:38:26

⑴ 如何用C語言編寫一個簡單的聊天室程序

這樣:

#include <stdlib.h>

#include <stdio.h>

#include <errno.h>

#include <string.h>

#include <unistd.h>

#include <netdb.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <sys/types.h>

#include <arpa/inet.h>

#include <pthread.h>

#define MAXLINE 100;

void *threadsend(void *vargp);

void *threadrecv(void *vargp);

int main()

{

int *clientfdp;

clientfdp = (int *)malloc(sizeof(int));

*clientfdp = socket(AF_INET,SOCK_STREAM,0);

struct sockaddr_in serveraddr;

struct hostent *hp;

bzero((char *)&serveraddr,sizeof(serveraddr));

serveraddr.sin_family = AF_INET;

serveraddr.sin_port = htons(15636);

serveraddr.sin_addr.s_addr = inet_addr("127.0.0.1");

if(connect(*clientfdp,(struct sockaddr *)&serveraddr,sizeof(serveraddr)) < 0){

printf("connect error ");

exit(1);

}

pthread_t tid1,tid2;

printf("connected ");

while(1){

pthread_create(&tid1,NULL,threadsend,clientfdp);

pthread_create(&tid2,NULL,threadrecv,clientfdp);

}

return EXIT_SUCCESS;

}

void *threadsend(void * vargp)

{

//pthread_t tid2;

int connfd = *((int *)vargp);

int idata;

char temp[100];

while(1){

//printf("me: ");

fgets(temp,100,stdin);

send(connfd,temp,100,0);

printf(" client send OK ");

}

printf("client send ");

return NULL;

}

void *threadrecv(void *vargp)

{

char temp[100];

int connfd = *((int *)vargp);

while(1){

int idata = 0;

idata = recv(connfd,temp,100,0);

if(idata > 0){

printf("server : %s ",temp);

}

}

return NULL;

}

(1)socket編程聊天室擴展閱讀:

注意事項

linux編譯多線程代碼時,shell提示找不到 pthread_create函數,原因是 pthread.h不是linux系統默認載入的庫文件,應該使用類似如下gcc命令進行編譯:

gcc echoserver.c -lpthread -o echoserver

只要注意 -lpthread參數就可以了。

熱點內容
免費nvr伺服器搭建 發布:2025-05-10 16:45:20 瀏覽:845
宏傑文件夾加密怎麼樣 發布:2025-05-10 16:40:16 瀏覽:505
我的世界java伺服器種子 發布:2025-05-10 16:38:51 瀏覽:273
linux做存儲伺服器要什麼配置 發布:2025-05-10 16:26:39 瀏覽:430
note3桌面文件夾 發布:2025-05-10 16:18:39 瀏覽:944
漆晝之翁密碼是多少 發布:2025-05-10 15:52:55 瀏覽:846
linux與windows的分區 發布:2025-05-10 15:40:18 瀏覽:996
搜狐視頻破解緩存 發布:2025-05-10 15:39:06 瀏覽:807
存儲器主要用來 發布:2025-05-10 15:17:34 瀏覽:427
兩台伺服器怎麼部署redis 發布:2025-05-10 15:16:09 瀏覽:903