Skip to content

Commit

Permalink
add socket
Browse files Browse the repository at this point in the history
  • Loading branch information
xiabo committed Dec 2, 2021
1 parent db00d2e commit 303094a
Show file tree
Hide file tree
Showing 7 changed files with 449 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
.vscode/

# Prerequisites
*.d

Expand Down
81 changes: 81 additions & 0 deletions csmodel/cppexample/client.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
#include <iostream>
#include <string>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <netdb.h>
#include <sys/uio.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <fstream>
using namespace std;
//Client side
int main(int argc, char *argv[])
{
//we need 2 things: ip address and port number, in that order
if(argc != 3)
{
cerr << "Usage: ip_address port" << endl; exit(0);
} //grab the IP address and port number
char *serverIp = argv[1]; int port = atoi(argv[2]);
//create a message buffer
char msg[1500];
//setup a socket and connection tools
struct hostent* host = gethostbyname(serverIp);
sockaddr_in sendSockAddr;
bzero((char*)&sendSockAddr, sizeof(sendSockAddr));
sendSockAddr.sin_family = AF_INET;
sendSockAddr.sin_addr.s_addr =
inet_addr(inet_ntoa(*(struct in_addr*)*host->h_addr_list));
sendSockAddr.sin_port = htons(port);
int clientSd = socket(AF_INET, SOCK_STREAM, 0);
//try to connect...
int status = connect(clientSd,
(sockaddr*) &sendSockAddr, sizeof(sendSockAddr));
if(status < 0)
{
cout<<"Error connecting to socket!"<<endl;
}
cout << "Connected to the server!" << endl;
int bytesRead, bytesWritten = 0;
struct timeval start1, end1;
gettimeofday(&start1, NULL);
while(1)
{
cout << ">";
string data;
getline(cin, data);
memset(&msg, 0, sizeof(msg));//clear the buffer
strcpy(msg, data.c_str());
if(data == "exit")
{
send(clientSd, (char*)&msg, strlen(msg), 0);
break;
}
bytesWritten += send(clientSd, (char*)&msg, strlen(msg), 0);
cout << "Awaiting server response..." << endl;
memset(&msg, 0, sizeof(msg));//clear the buffer
bytesRead += recv(clientSd, (char*)&msg, sizeof(msg), 0);
if(!strcmp(msg, "exit"))
{
cout << "Server has quit the session" << endl;
break;
}
cout << "Server: " << msg << endl;
}
gettimeofday(&end1, NULL);
close(clientSd);
cout << "********Session********" << endl;
cout << "Bytes written: " << bytesWritten <<
" Bytes read: " << bytesRead << endl;
cout << "Elapsed time: " << (end1.tv_sec- start1.tv_sec)
<< " secs" << endl;
cout << "Connection closed" << endl;
return 0;
}
112 changes: 112 additions & 0 deletions csmodel/cppexample/server.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
#include <iostream>
#include <string>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <netdb.h>
#include <sys/uio.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <fstream>
using namespace std;
//Server side
int main(int argc, char *argv[])
{
//for the server, we only need to specify a port number
if(argc != 2)
{
cerr << "Usage: port" << endl;
exit(0);
}
//grab the port number
int port = atoi(argv[1]);
//buffer to send and receive messages with
char msg[1500];

//setup a socket and connection tools
sockaddr_in servAddr;
bzero((char*)&servAddr, sizeof(servAddr));
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
servAddr.sin_port = htons(port);

//open stream oriented socket with internet address
//also keep track of the socket descriptor
int serverSd = socket(AF_INET, SOCK_STREAM, 0);
if(serverSd < 0)
{
cerr << "Error establishing the server socket" << endl;
exit(0);
}
//bind the socket to its local address
int bindStatus = bind(serverSd, (struct sockaddr*) &servAddr,
sizeof(servAddr));
if(bindStatus < 0)
{
cerr << "Error binding socket to local address" << endl;
exit(0);
}
cout << "Waiting for a client to connect..." << endl;
//listen for up to 5 requests at a time
listen(serverSd, 5);
//receive a request from client using accept
//we need a new address to connect with the client
sockaddr_in newSockAddr;
socklen_t newSockAddrSize = sizeof(newSockAddr);
//accept, create a new socket descriptor to
//handle the new connection with client
int newSd = accept(serverSd, (sockaddr *)&newSockAddr, &newSockAddrSize);
if(newSd < 0)
{
cerr << "Error accepting request from client!" << endl;
exit(1);
}
cout << "Connected with client!" << endl;
//lets keep track of the session time
struct timeval start1, end1;
gettimeofday(&start1, NULL);
//also keep track of the amount of data sent as well
int bytesRead, bytesWritten = 0;
while(1)
{
//receive a message from the client (listen)
cout << "Awaiting client response..." << endl;
memset(&msg, 0, sizeof(msg));//clear the buffer
bytesRead += recv(newSd, (char*)&msg, sizeof(msg), 0);
if(!strcmp(msg, "exit"))
{
cout << "Client has quit the session" << endl;
break;
}
cout << "Client: " << msg << endl;
cout << ">";
string data;
getline(cin, data);
memset(&msg, 0, sizeof(msg)); //clear the buffer
strcpy(msg, data.c_str());
if(data == "exit")
{
//send to the client that server has closed the connection
send(newSd, (char*)&msg, strlen(msg), 0);
break;
}
//send the message to client
bytesWritten += send(newSd, (char*)&msg, strlen(msg), 0);
}
//we need to close the socket descriptors after we're all done
gettimeofday(&end1, NULL);
close(newSd);
close(serverSd);
cout << "********Session********" << endl;
cout << "Bytes written: " << bytesWritten << " Bytes read: " << bytesRead << endl;
cout << "Elapsed time: " << (end1.tv_sec - start1.tv_sec)
<< " secs" << endl;
cout << "Connection closed..." << endl;
return 0;
}
66 changes: 66 additions & 0 deletions csmodel/echoClient.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define MAXLINE 4096 /*max text line length*/
#define SERV_PORT 3000 /*port*/

int
main(int argc, char **argv)
{
int sockfd;
struct sockaddr_in servaddr;
char sendline[MAXLINE], recvline[MAXLINE];

//basic check of the arguments
//additional checks can be inserted
if (argc !=2) {
perror("Usage: TCPClient <IP address of the server");
exit(1);
}

//Create a socket for the client
//If sockfd<0 there was an error in the creation of the socket
if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) <0) {
perror("Problem in creating the socket");
exit(2);
}

//Creation of the socket
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr(argv[1]);
servaddr.sin_port = htons(SERV_PORT); //convert to big-endian order

//Connection of the client to the socket
if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr))<0) {
perror("Problem in connecting to the server");
exit(3);
}
printf("> ");

while (fgets(sendline, MAXLINE, stdin) != NULL) {
if(strstr(sendline, "exit") == sendline)
{
close(sockfd);
break;
}
send(sockfd, sendline, strlen(sendline), 0);
memset(recvline, 0, MAXLINE);
if (recv(sockfd, recvline, MAXLINE, 0) == 0){
//error: server terminated prematurely
perror("The server terminated prematurely");
exit(4);
}
// printf("\n", "String received from the server: ");
// fputs(recvline, stdout);
printf("%s\n> ", recvline);
}
printf("socket close\n");
exit(0);
}
66 changes: 66 additions & 0 deletions csmodel/echoServer.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>

#define MAXLINE 4096 /*max text line length*/
#define SERV_PORT 3000 /*port*/
#define LISTENQ 8 /*maximum number of client connections */

int main (int argc, char **argv)
{
int listenfd, connfd, n;
pid_t childpid;
socklen_t clilen;
char buf[MAXLINE];
struct sockaddr_in cliaddr, servaddr;

//creation of the socket
listenfd = socket (AF_INET, SOCK_STREAM, 0);

//preparation of the socket address
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(SERV_PORT);

bind (listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr));

listen (listenfd, LISTENQ);

printf("%s\n","Server running...waiting for connections.");

for ( ; ; ) {

clilen = sizeof(cliaddr);
connfd = accept (listenfd, (struct sockaddr *) &cliaddr, &clilen);
printf("%s\n","Received request...");

while ( (n = recv(connfd, buf, MAXLINE, 0)) > 0) {
printf("%s","----- String received from and resent to the client: -----\n");
buf[n-1] = 0;
puts(buf);
printf("%lu\n",strlen(buf));
if (strstr(buf, "hello server") == buf){
send(connfd, "hello client", 12, 0);
continue;
}
if (strlen(buf) == 0){
send(connfd, "?", 2, 0);
continue;
}
send(connfd, buf, n, 0);
}

if (n < 0) {
perror("Read error");
exit(1);
}
close(connfd);

}
//close listening socket
close (listenfd);
}
62 changes: 62 additions & 0 deletions socket/client.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// https://www.linuxhowtos.org/C_C++/socket.htm

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

void error(const char *msg)
{
perror(msg);
exit(0);
}

int main(int argc, char *argv[])
{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;

char buffer[256];
if (argc < 3) {
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
// 连接端口
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
printf("Please enter the message: ");
bzero(buffer,256);
fgets(buffer,255,stdin);
// 写入数据
n = write(sockfd,buffer,strlen(buffer));
if (n < 0)
error("ERROR writing to socket");
bzero(buffer,256);
// 读取数据
n = read(sockfd,buffer,255);
if (n < 0)
error("ERROR reading from socket");
printf("%s\n",buffer);
close(sockfd);
return 0;
}
Loading

0 comments on commit 303094a

Please sign in to comment.