学习网络编程第二天作业

使用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

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值