TCP一对一双向通信
服务器:
#include "/home/ubuntu/myhead.h"
int con_fd = -1;
void *recv_to_cilent(void *arg)
{
char *buf = malloc(100);
while(1)
{
memset(buf,0,100);
recv(con_fd,buf,100,0);
printf("from cilent:%s\n",buf);
}
}
//一对一双向
int main(int argc,char **argv)
{
int sock_fd = socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_in serve, cilent;
serve.sin_family = AF_INET;
serve.sin_port = htons(atoi(argv[2]));
serve.sin_addr.s_addr = inet_addr(argv[1]);
socklen_t serve_len = sizeof(serve);
socklen_t cilent_len =sizeof(cilent);
bind(sock_fd,&serve,serve_len);
listen(sock_fd,4);
printf("等待连接.....\n");
con_fd = accept(sock_fd,&cilent,&cilent_len);
printf("连接成功!!!!\n");
pthread_t tid;
pthread_create(&tid,NULL, recv_to_cilent,NULL);
char *buf = malloc(100);
while(1)
{
memset(buf,0,100);
fgets(buf,100,stdin);
send(con_fd,buf,100,0);
}
}
客户端:
#include "/home/ubuntu/myhead.h"
int sock_fd = -1;
void *cilent_to_serve(void *arg)
{
char *buf = malloc(100);
while(1)
{
memset(buf,0,100);
fgets(buf,100,stdin);
send(sock_fd,buf,100,0);
}
}
int main(int argc,char **argv)
{
sock_fd = socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_in serve, cilent;
serve.sin_family = AF_INET;
serve.sin_port = htons(atoi(argv[2]));
serve.sin_addr.s_addr = inet_addr(argv[1]);
socklen_t serve_len = sizeof(serve);
socklen_t cilent_len =sizeof(cilent);
bind(sock_fd,&serve,serve_len);
connect(sock_fd,&serve,serve_len);
pthread_t tid;
pthread_create(&tid,NULL, cilent_to_serve,NULL);
char *buf = malloc(100);
while(1)
{
memset(buf,0,100);
recv(sock_fd,buf,100,0);
printf("from serve:%s\n",buf);
}
}