/****************************
*******server.c************
****************************/
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <sys/un.h>
#include <unistd.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
extern int errno;
int main()
{
//step1 secket
int fd=socket(AF_INET,SOCK_STREAM,0);
fprintf(stderr,"socket id=%d\n",fd);
//setp2 bind
struct sockaddr_in servaddr;
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(7777);
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
printf("ip:%s port:%d\n",inet_ntoa(servaddr.sin_addr),ntohs(servaddr.sin_port));int ret=bind(fd,(struct sockaddr *)&servaddr,sizeof(servaddr));
if(ret<0)
{
fprintf(stderr,"error:%s\n",strerror(errno));
close(fd);
return -1;
}
//step3 linsten
listen(fd,5);
//setp4 accpet
int newfd;
struct sockaddr_in peer;
socklen_t size;
size=sizeof(peer);
printf("waiting for client connectting.......\n ");
newfd=accept(fd,(struct sockaddr *)&peer,&size);
//client ip port
printf("ip:%s port:%d\n",inet_ntoa(peer.sin_addr),ntohs(peer.sin_port));
char buf[100];
//step5 transform date
while(1)
{
fgets(buf,100,stdin);
write(newfd,buf,strlen(buf));
int cnt1=read(newfd,buf,100);
write(1,buf,cnt1);
}
close(newfd);
return 0;
}
/****************************
*******client.c************
****************************/
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <sys/un.h>
#include <unistd.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
extern int errno;
int main()
{
int fd=socket(AF_INET,SOCK_STREAM,0);
// server addr
struct sockaddr_in servaddr;
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(7777);
servaddr.sin_addr.s_addr = inet_addr("172.0.0.1");
// conecting..........
int ret=connect(fd,(struct scokaddr *)&servaddr,sizeof(servaddr));
if(ret<0)
{
fprintf(stderr,"error:%s\n",strerror(errno));
close(fd);
return -1;
}
char buf[100];
int cnt;
while(1)
{
cnt = read(fd,buf,100);
write(1,buf,cnt);
fgets(buf,100,stdin);
write(fd,buf,strlen(buf));
}
close(fd);
return 0;
}
分别编译与执行:
gcc tcpserver.c -o server
gcc tcpclient.c -o clent
在不同终端 运行 ./server ./clent
服务器先对客户机发信息 ,然后客户机在对服务器发信息 这样就可以互相通信
网络编程 客户端与服务器数据传输
最新推荐文章于 2018-12-28 13:38:28 发布