使用TCP实现客户端和服务器双向通信
代码:
服务器:
#include "/home/ubuntu/网络编程/myinc.h"
int con_ret = -1;
void* t1 (void * arg)
{
int fd = con_ret;
//发送消息
char *buf = malloc(100);
while(1)
{
memset(buf,0,100);
fgets(buf,100,stdin);
send(fd,buf,100,0);
}
}
int main(int argc, const char *argv[])
{
int sock_fd = socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_in serve,client;
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 client_len = sizeof(client);
bind(sock_fd,&serve,serve_len);
listen(sock_fd,4);
con_ret = accept(sock_fd,&client,&client_len);
pthread_t tid;
pthread_create(&tid,NULL,t1,NULL);
//接收
char* buf = malloc(100);
while(1)
{
memset(buf,0,100);
recv(con_ret,buf,100,0);
printf("from client :%s\n",buf);
}
return 0;
}
客户端:
#include "/home/ubuntu/网络编程/myinc.h"
int sock_fd = -1;
void* t1(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, const char *argv[])
{
sock_fd = socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_in serve,client;
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 client_len = sizeof(client);
bind(sock_fd,&serve,serve_len);
connect(sock_fd,&serve,serve_len);
pthread_t tid;
pthread_create(&tid,NULL,t1,NULL);
char* buf =malloc(100);
//读
while(1)
{
memset(buf,0,100);
recv(sock_fd,buf,100,0);
printf("form serve:%s\n",buf);
}
return 0;
}
头文件:
#ifndef __MYSTD__
#define __MYSTD__
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <semaphore.h>
#include <signal.h>
#include <pthread.h>
#include <dirent.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#endif