Linux C/S socket通信
2020-03-05 本文已影响0人
FakeCSer爱去网吧
server
#include <sys/types.h>//socket
#include <sys/socket.h>//socket,bind,listen,accept,connect
#include <unistd.h>
#include <iostream>
using namespace std;
#include <arpa/inet.h>//itons,inet_aton
#include <netinet/in.h>//inet_aton
#include <cstring>//bzero
#define PORT 6666
int main()
{
char buf[BUFSIZ];
struct sockaddr_in serveraddr;
struct sockaddr_in clientaddr;
int listenfd,connectfd;
socklen_t addrlen;//accept中最后一个参数
int ret,n;
char clientip[20];
listenfd = socket(AF_INET,SOCK_STREAM,0);
if(listenfd==-1)
{
perror("socket");
exit(1);
}
//端口复用
int on = 1;
if(setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(int))<0)
{
perror("setsockopt");
exit(1);
}
bzero(&serveraddr,sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_port = htons(PORT);
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
// inet_pton(AF_INET,"127,0,0,1",&serveraddr.sin_addr.saddr);
ret = bind(listenfd,(struct sockaddr*)&serveraddr,sizeof(serveraddr));
if(ret == -1)
{
perror("bind");
exit(1);
}
ret = listen(listenfd,128);
if(ret == -1)
{
perror("listen");
exit(1);
}
else
{
cout << "等待连接····"<<endl;
}
addrlen = sizeof(clientaddr);
connectfd = accept(listenfd,(struct sockaddr*)&clientaddr,&addrlen);
if(connectfd == -1)
{
perror("accept");
exit(1);
}
else
{
cout << "client have connected" <<endl;
}
inet_ntop(AF_INET,&clientaddr.sin_addr.s_addr,clientip,sizeof(clientip));
cout << "clinet ip: "<< (char *)clientip << endl;
cout << "clinet port: "<< ntohs(clientaddr.sin_port)<<endl;;
/****数据传输*********/
while(1)
{
n = read(connectfd,buf,sizeof(buf));
if(n == 0)//n返回值为0表示读取结束,即客户端关闭
{
cout << "client closed"<<endl;
break;//跳出循环
}
cout << buf << endl;
write(connectfd,buf,sizeof(buf));
bzero(buf,sizeof(buf));
}
/****************/
close(listenfd);
close(connectfd);
return 0;
}
client
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <iostream>
using namespace std;
#include <cstring>
#include <netinet/in.h>//inet_aton
#include <arpa/inet.h>//itons,inet_aton
#define PORT 6666
#define BUFSIZE 1024
int main()
{
int fd;
struct sockaddr_in serveraddr;
fd = socket(AF_INET,SOCK_STREAM,0);
char sndbuf[BUFSIZE];
char rcvbuf[BUFSIZE];
bzero(&serveraddr,sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_port = htons(PORT);
inet_pton(AF_INET,"127,0,0,1",&serveraddr.sin_addr);
if(connect(fd,(struct sockaddr*)&serveraddr,sizeof(serveraddr))==-1)
{
perror("connect");
exit(1);
}
else
{
cout<< "server have connected"<<endl;
}
/*************/
while(cin >> sndbuf)
{
write(fd,sndbuf,sizeof(sndbuf));
read(fd,rcvbuf,sizeof(rcvbuf));
cout << "服务器:recieved "<<rcvbuf << endl;
bzero(sndbuf,sizeof(sndbuf));
bzero(rcvbuf,sizeof(rcvbuf));
}
/*************/
close(fd);
return 0;
}