1.å¦ä½ç¨Cè¯è¨ç¼åä¸ä¸ªç®åçè天室ç¨åº
å¦ä½ç¨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 ;
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();
serveraddr.sin_addr.s_addr = inet_addr(".0.0.1");
if(connect(*clientfdp,(struct sockaddr *)&serveraddr,sizeof(serveraddr)) < 0){
printf("connect error\n");
exit(1);
}
pthread_t tid1,tid2;
printf("connected\n");
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[];
while(1){
//printf("me: \n ");
fgets(temp,,stdin);
send(connfd,temp,,0);
printf(" client send OK\n");
}
printf("client send\n");
return NULL;
}
void *threadrecv(void *vargp)
{
char temp[];
int connfd = *((int *)vargp);
while(1){
int idata = 0;
idata = recv(connfd,temp,,0);
if(idata > 0){
printf("server :\n%s\n",temp);
}
}
return NULL;
}
æ©å±èµæï¼æ³¨æäºé¡¹
linuxä¸ç¼è¯å¤çº¿ç¨ä»£ç æ¶ï¼shellæ示æ¾ä¸å° pthread_createå½æ°ï¼åå æ¯ pthread.hä¸æ¯linuxç³»ç»é»è®¤å è½½çåºæ件ï¼åºè¯¥ä½¿ç¨ç±»ä¼¼å¦ä¸gccå½ä»¤è¿è¡ç¼è¯ï¼
gcc echoserver.c -lpthread -o echoserver
åªè¦æ³¨æ -lpthreadåæ°å°±å¯ä»¥äºã