//服务器
#include"myhead.h"
int con_fd=-1;
//子线程接收
void* fun_recv(void*argv)
{
char*buf=malloc(100);
while(1)
{
memset(buf,0,100);
//接收消息
int n=recv(con_fd, buf, 100, 0);
if(n==0)
{
break;
}
printf("client:%s\n",buf);
}
}
int main(int argc, char*argv[])
{
//1.创建套接字
int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
//网际协议,套接字类型TCP选择流式套接字
if(-1 == sock_fd)
{
perror("creat sock_fd failed");
return -1;
}
//2.绑定服务器的IP地址+端口号
//定义结构体
struct sockaddr_in serve,client;
serve.sin_family = AF_INET;//地址族成员
serve.sin_port = htons(atoi(argv[1]));//0-------65535
serve.sin_addr.s_addr = inet_addr(argv[2]);//需要把点分式字符串转换为无符号的32位网络地址in_addr_t,
socklen_t serve_len = sizeof(serve);
socklen_t client_len = sizeof(client);
//绑定函数
int ret = bind(sock_fd, (struct sockaddr *)&serve, serve_len);
if(ret == -1)
{
perror("bind failed");
}
//3.监听
int listen_ret = listen(sock_fd, 4);//可以设置监听的套接字的最大个数
//4.等待连接
printf("等待连接....\n");
con_fd = accept(sock_fd, (struct sockaddr *)&client, &client_len);//阻塞等待
printf("连接成功!!!\n");
pthread_t tid;
//创建线程
pthread_create(&tid, NULL, fun_recv, NULL);
char* buf=malloc(100);
//主进程发送
while(1)
{
memset(buf,0,100);
//发消息
fgets(buf,100,stdin);
send(con_fd,buf,100,0);
}
}
//客户端
#include"myhead.h"
int sock_fd=-1;
//子线程发送
void* fun_send(void*argv)
{
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[])
{
//1.创建套接字
sock_fd = socket(AF_INET, SOCK_STREAM, 0);
//网际协议,套接字类型TCP选择流式套接字
if(-1 == sock_fd)
{
perror("creat sock_fd failed");
return -1;
}
//2.绑定服务器的IP地址+端口号
//定义结构体
struct sockaddr_in serve,client;
serve.sin_family = AF_INET;//地址族成员
serve.sin_port = htons(atoi(argv[1]));//0-------65535
serve.sin_addr.s_addr = inet_addr(argv[2]);//需要把点分式字符串转换为无符号的32位网络地址in_addr_t,
socklen_t serve_len = sizeof(serve);
socklen_t client_len = sizeof(client);
//绑定函数
int ret = bind(sock_fd, (struct sockaddr *)&serve, serve_len);
if(ret == -1)
{
perror("bind failed");
}
//发起连接
connect(sock_fd,(struct sockaddr *)&serve,serve_len);
pthread_t tid;
//创建线程
pthread_create(&tid, NULL, fun_send, NULL);
char* buf=malloc(100);
//主进程接收
while(1)
{
memset(buf,0,100);
//接收消息
int n=recv(sock_fd, buf, 100, 0);
if(n==0)
{
break;
}
printf("serve:%s\n",buf);
}
}
8月20日 TCP实现客户端和服务器双向通信
于 2024-08-21 12:38:10 首次发布