#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cerrno>
#include <cstring>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>
using namespace std;
int main()
{
cout << "this is client" <<endl;
int client = socket(AF_INET, SOCK_STREAM, 0);
if(client == -1)
{
cout << " socket err " <<endl;
return 0;
}
struct sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(7637);
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
if(connect(client, (struct sockaddr_in*) &serverAddr, sizeof(serverAddr)) < 0)
{
cout << "connect err" <<endl;
return 0;
}
cout << "connect ...." <<endl;
char data[255];
char buf[255];
while (true)
{
cin >> data;
send(client, data, strlen(data), 0);
if(strcmp(data, "exit") == 0 || strcmp(data, "EXIT") == 0)
{
cout << "client disconnect ..." <<endl;
break;
}
memset(buf, 0 ,sizeof(buf));
int len = recv(client, buf, sizeof(buf), 0);
buf[len] = '\0';
cout << buf << endl;
}
close(client);
return 0;
}
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cerrno>
#include <cstring>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>
using namespace std;
int main()
{
cout << "this is server" <<endl;
int listenfd = socket(AF_INET, SOCK_STREAM, 0);
if (listenfd == -1)
{
cout << "socker err " <<endl;
return 0;
}
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(7637);
addr.sin_addr.s_addr = INADDR_ANY;
if(bind(listenfd, (struct sockaddr*) &addr,sizeof(addr)) == -1)
{
cout << "bind err" <<endl;
return 0;
}
if(listen(listenfd , 5) == -1)
{
cout <<"listen err" <<endl;
}
int conn;
char clientIP[INET_ADDRSTRLEN] = "";
struct sockaddr_in clientAddr;
socklen_t clinetAddrLen = sizeof(clientAddr);
while (true)
{
cout << "listen ...." <<endl;
conn = accept(listenfd, (struct sockaddr*)&clientAddr, &clinetAddrLen);
if(conn < 0)
{
cout <<"conn accept err " <<endl;
continue;
}
inet_ntop(AF_INET, &clientAddr.sin_addr, clientIP, INET_ADDRSTRLEN);
cout << " connect " << clientIP << ":" << ntohs(clientAddr.sin_port) << endl;
char buf[255];
while (true)
{
memset(buf, 0 , sizeof(buf));
int len = recv(conn, buf, sizeof(buf), 0);
buf[len] = '\0';
if(strcmp(buf,"exit") == 0 || strcmp(buf,"EXIT") == 0)
{
cout << "disconnect " << clientIP << ":" <<ntohs(clientAddr.sin_port) << endl;
break;
}
cout << buf << endl;
send(conn, buf, len,0)
}
close(conn);
}
close(listenfd);
return 0;
}