Server.c
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#define IPADDRESS "127.0.0.1"
#define PORT 8848
#define BUF_SIZE 1024
void* SendMes_Thread(void* Arg)
{
puts("Thread created.");
int* Client_Socket=(int*)Arg;
char Mes_Buf[BUF_SIZE]={0};
while(1)
{
scanf("%s",Mes_Buf);
send(*Client_Socket,Mes_Buf,strlen(Mes_Buf)+1,0);
bzero(Mes_Buf,BUF_SIZE);
}
close(*Client_Socket);
return NULL;
}
int main(int Argc,char** Argv)
{
int Server_Socket=socket(AF_INET,SOCK_STREAM,0);
if(-1==Server_Socket)
{
perror("Server socket creation failed!");
return -1;
}
struct sockaddr_in Server_NetInfo={0};
Server_NetInfo.sin_family=AF_INET;
Server_NetInfo.sin_addr.s_addr=inet_addr(IPADDRESS);
Server_NetInfo.sin_port=htons(PORT);
if(-1==bind(Server_Socket,(const struct sockaddr*)&Server_NetInfo,sizeof(struct sockaddr)))
{
perror("Binding failure!");
return -1;
}
if(-1==listen(Server_Socket,6))
{
perror("Linstening the to failure!");
return -1;
}
socklen_t Client_NetInfoSize=sizeof(struct sockaddr_in);
struct sockaddr_in Client_NetInfo={0};
int Client_Socket=-1;
Client_Socket=accept(Server_Socket,(struct sockaddr*)&Client_NetInfo,&Client_NetInfoSize);
if(-1==Client_Socket)
{
perror("Accepting fainure!");
}
pthread_t Thread_ID=-1;
if(-1==pthread_create(&Thread_ID,NULL,SendMes_Thread,(void*)&Client_Socket))
{
puts("Create thread falied!");
return -1;
}
char Mes_Buf[BUF_SIZE]={0};
while(1)
{
if(0==recv(Client_Socket,Mes_Buf,BUF_SIZE,0))
{
puts("Client is desconnected!");
break;
}
printf("Client: %s\n",Mes_Buf);
}
close(Server_Socket);
return 0;
}
Client.c
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#define IPADDRESS "127.0.0.1"
#define PORT 8848
#define BUF_SIZE 1024
void* RecvMes_Thread(void* Arg)
{
int* Client_Socket=(int*)Arg;
char Mes_Buf[BUF_SIZE]={0};
while(1)
{
if(0==recv(*Client_Socket,Mes_Buf,BUF_SIZE,0))
{
perror("Server is disconnected!");
break;
}
printf("Server: %s\n",Mes_Buf);
}
close(*Client_Socket);
return NULL;
}
int main(int Argc,char** Argv)
{
int Client_Socket=socket(AF_INET,SOCK_STREAM,0);
if(-1==Client_Socket)
{
perror("Client socket creation failed!");
return -1;
}
printf("Client_Socket==%d\n",Client_Socket);
struct sockaddr_in Server_NetInfo={0};
Server_NetInfo.sin_family=AF_INET;
Server_NetInfo.sin_addr.s_addr=inet_addr(IPADDRESS);
Server_NetInfo.sin_port=htons(PORT);
if(-1==connect(Client_Socket,(const struct sockaddr*)&Server_NetInfo,sizeof(struct sockaddr_in)))
{
perror("Connecting failure!");
return -1;
}
pthread_t Thread_ID=-1;
if(0==pthread_create(&Thread_ID,NULL,RecvMes_Thread,(void*)&Client_Socket))
{
puts("Create thread failed!");
}
char Mes_Buf[BUF_SIZE]={0};
while(1)
{
scanf("%s",Mes_Buf);
if(-1==send(Client_Socket,Mes_Buf,strlen(Mes_Buf)+1,0))
{
perror("Sending failure!");
break;
}
bzero(Mes_Buf,BUF_SIZE);
}
close (Client_Socket);
return 0;
}