日期:2014-05-16  浏览次数:20744 次

socket编程 哪位高手帮我看看下面的问题,为什么输出结果会这样,帮我解释解释
我只在客户端输入一个a,然后会车
[root@heiying have_test]# ./server_thread
com_fd=4
new_fd=4
Message from client: f
Message from client: 


[root@heiying have_test]# ./client
please input a chars 
f
snd_buf = f
Message form server: a
please input a chars 
snd_buf = 

Message form server: a
please input a chars 


服务端:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <netdb.h>
#include <pthread.h>


#define PORT 8888

//线程执行函数负责读写
void *thr_fn(void *arg)
{
int size,j;
  //char recv_buf[100];
char recv_buf;
int *parg=(int *)arg;
int new_fd=*parg;
printf("new_fd=%d\n",new_fd);
while(1)
{
read(new_fd,&recv_buf, sizeof(recv_buf));
printf("Message from client: %c\n",recv_buf);
recv_buf = 'a';
write(new_fd, &recv_buf, sizeof(recv_buf));
}
close(new_fd);
return 0;
}


int main(int argc,char *argv[])
{
  socklen_t clt_addr_len;
int listen_fd;
int com_fd;
int ret;
int i;
int len;
//static char recv_buf;

pthread_t tid;

struct sockaddr_in clt_addr;
struct sockaddr_in srv_addr;


//创建套接字用于服务器的监听 
listen_fd=socket(PF_INET,SOCK_STREAM,0);
if(listen_fd<0)
{
perror("cannot create listening socket");
return 1;
}

//填充关于服务器的套节字信息
memset(&srv_addr,0,sizeof(srv_addr));
srv_addr.sin_family=AF_INET;
srv_addr.sin_addr.s_addr=htonl(INADDR_ANY);
//srv_addr.sin_port=htons(port);
srv_addr.sin_port=htons(PORT);


//将服务器和套节字绑定
ret=bind(listen_fd,(struct sockaddr *)&srv_addr,sizeof(srv_addr));
if(ret==-1)
{
perror("cannot bind server socket");
close(listen_fd);
return 1;
}

//监听指定端口,连接5个客户端 
ret=listen(listen_fd,5);
if(ret==-1)
{
perror("cannot listen the client connect request");
close(listen_fd);
return 1;
}
while(1)
{
len=sizeof(clt_addr);
com_fd=accept(listen_fd,(struct sockaddr *)&clt_addr,&len);
if(com_fd<0)
{
if(errno==EINTR)
{
continue;
}
else
{
perror("cannot accept client connect request");
close(listen_fd);
return 1;
}
}
printf("com_fd=%d\n",com_fd);//打印建立连接的客户端产生的套节字
if((pthread_create(&tid,NULL,thr_fn,&com_fd))==-1)
{
perror("pthread_create error");
close(listen_fd);
close(com_fd);
return 1;
}
}
return 0;
}



客户端程序:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netdb.h>
#include <unistd.h>

#define PORT 8888
#define SERVER_IP "192.168.1.119"


int main(int argc,char *argv[])
{
  int connect_fd;
int ret;
//char snd_buf[100];
char snd_buf;
int i;
//int port;
int len;

static struct sockaddr_in srv_addr;


//创建套节字用于客户端的连接
connect_fd=socket(PF_INET,SOCK_STREAM,0);
if(connect_fd<0)
{
perror("cannot create communication socket");
return 1;
}

//