当前位置:首页 » 编程软件 » 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参数就可以了。

热点内容
亚索后q脚本 发布:2025-02-08 14:21:06 浏览:324
官方源码 发布:2025-02-08 14:09:25 浏览:437
python过滤器 发布:2025-02-08 14:05:06 浏览:617
火山币算法 发布:2025-02-08 14:04:49 浏览:669
jffs2解压 发布:2025-02-08 13:55:15 浏览:388
如何向服务器发送大数据包 发布:2025-02-08 13:55:12 浏览:662
服务器pop地址是什么 发布:2025-02-08 13:39:21 浏览:386
网站访问计数器 发布:2025-02-08 13:32:07 浏览:6
钓鱼的腥怎么配置 发布:2025-02-08 13:22:57 浏览:756
php数组的引用 发布:2025-02-08 13:22:54 浏览:96