client:
#include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <signal.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #include <iostream> using namespace std; #define bufsize 1024 int main(int argc,char* argv[]) { const char* ip = argv[1]; int port = atoi(argv[2]); struct sockaddr_in server_address; memset(&server_address,0,sizeof(server_address)); server_address.sin_family = AF_INET; server_address.sin_port = htons(port); inet_pton(AF_INET,ip,&server_address.sin_addr); int sockfd = socket(AF_INET,SOCK_STREAM,0); //int sockfd1 = socket(AF_INET,SOCK_STREAM,0); if(sockfd<0){cout<<"socket failed"<<endl;} int connfd = connect(sockfd,(struct sockaddr*)&server_address,sizeof(server_address)); if(connfd<0){cout<<"connect failed"<<endl;} char buffer_recv[bufsize]; char buffer_send[bufsize]; while(1){ memset(buffer_send,0,bufsize); memset(buffer_recv,0,bufsize); cout<<"client:"; fgets(buffer_send,bufsize-1,stdin); send(sockfd,buffer_send,strlen(buffer_send),0); int num = recv(sockfd,buffer_recv,bufsize-1,0); cout<<"server:"<<buffer_recv<<endl; } close(connfd); close(sockfd); return 0; }
server:
#include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <signal.h> #include <assert.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <iostream> using namespace std; #define bufsize 1024 //#define port 8888 #define backlog 10 int main(int argc,char* argv[]) { const char* ip = argv[1]; int port = atoi(argv[2]); struct sockaddr_in address; bzero(&address,sizeof(address));//qing ling address.sin_family = AF_INET; address.sin_port = htons(port); //address.sin_addr.s_addr = INADDR_ANY; inet_pton(AF_INET,ip,&address.sin_addr); int sock = socket(AF_INET,SOCK_STREAM,0); if(sock<0){cout<<"socket failed"<<endl;} int ret = bind(sock,(struct sockaddr*)&address,sizeof(address)); if(ret < 0){cout<<"bind failed"<<endl;} ret = listen(sock,backlog); if(ret < 0){cout<<"listen failed"<<endl;} struct sockaddr_in client ; socklen_t client_addrlength = sizeof(client); int connfd = accept(sock,(struct sockaddr*)&client,&client_addrlength); if(connfd<0){cout<<"connect failed"<<endl;} char buffer_recv[bufsize]; char buffer_send[bufsize]; while(1) { memset(buffer_recv,0,bufsize); memset(buffer_send,0,bufsize); int rev = recv(connfd,buffer_recv,bufsize -1 ,0); cout<<"client:"<<buffer_recv<<endl; cout<<"server:"; fgets(buffer_send,bufsize,stdin); send(connfd,buffer_send,strlen(buffer_send),0); } close(connfd); close(sock); return 0; }