服务器端:
#include
#include
#include
#include
#include
#include
using namespace std;
void *run(void *arg);
int main(void)
{
int fd=0,res=0;
unsigned int port=8888;
struct sockaddr_in my_addr;
//init sockaddr_in
//bzero(my_addr,sizeof(my_addr));
my_addr.sin_family=AF_INET;
my_addr.sin_port=htons(port);
my_addr.sin_addr.s_addr=htonl(INADDR_ANY);
//1,create tcp socket
fd=socket(AF_INET,SOCK_STREAM,0);
if(fd<0)
{
perror("socket");
exit(-1);
}
cout<
//2,bind sockfd with sockaddr
res = bind(fd,(struct sockaddr *)&my_addr,sizeof(my_addr));
if(res!=0)
{
perror("bind");
close(fd);
exit(-1);
}
cout<
//3,switch active to unactive
res = listen(fd,10);
if(res!=0)
{
perror("bind");
close(fd);
exit(-1);
}
cout<
//4,waiting and accept client connect request...
int client_fd=0;
unsigned client_port=0;
char client_ip[20];
pthread_t tid;
sockaddr_in client_addr;
socklen_t socklen = sizeof(client_addr);
cout<
while(1)
{
client_fd = accept(fd,(struct sockaddr *)&client_addr,&socklen);
if(client_fd<0)
{
perror("accept");
close(fd);
exit(-1);
}
//get client ip and port
inet_ntop(AF_INET,&client_addr.sin_addr.s_addr,client_ip,sizeof(client_ip));
client_port = ntohs(client_addr.sin_port);
cout<
//create new thread handle client
pthread_create(&tid,NULL,run,(void *)client_fd);
pthread_detach(tid);
}
close(fd);
return 0;
}
void *run(void *arg)//thread execute function
{
int client_fd = (int)arg;
int len=0;
char *buf[512];
while(1)
{
len = read(client_fd,buf,sizeof(buf));//read data from client
if(len==0)
{
cout<
close(client_fd);
break;
}
len = write(client_fd,buf,len);//echo to client
}
return NULL;
}
客户端:
#include
#include
#include
#include
#include
#include
using namespace std;
int main(void)
{
int fd=0,res=0,len=0;
unsigned int server_port = 8888;
const char *server_ip = "192.168.1.19";
char sendbuf[512]="",getbuf[512]="";
struct sockaddr_in server;
//init server sockaddr
server.sin_family = AF_INET;
server.sin_port = htons(server_port);
inet_pton(AF_INET,server_ip,&server.sin_addr.s_addr);
//create tcp socket
fd = socket(AF_INET,SOCK_STREAM,0);
if(fd<0)
{
perror("socket");
exit(-1);
}
cout<
//connect to server...
res = connect(fd,(struct sockaddr *)&server,sizeof(server));
if(res!=0)
{
perror("connect");
close(fd);
exit(-1);
}
cout<
while(1)
{
cout<:";
cin.getline(sendbuf,sizeof(sendbuf));
send(fd,sendbuf,strlen(sendbuf),0);//send data to server
len = recv(fd,getbuf,sizeof(getbuf),0);//receive data from server
getbuf[len]='\0';
if(len==0)
{
cout<
close(fd);
break;
}
cout<
}
return 0;
}