服务器端:
- #include<stdio.h>
- #include<stdlib.h>
- #include<errno.h>
- #include<string.h>
- #include<sys/types.h>
- #include<sys/wait.h>
- #include<sys/socket.h>
- #include<netinet/in.h>
- #include<arpa/inet.h>
- #include<iostream>
- using namespace std;
- #define PORT 4002
- #define BACKLOG 5
- int main()
- {
- int listensock, clientsock;
- struct sockaddr_in local_addr;
- struct sockaddr_in client_addr;
- char buf[1024];
- if((listensock = socket(AF_INET,SOCK_STREAM, 0)) == -1)
- {
- cout << "socket create error" << endl;
- exit(1);
- }
- local_addr.sin_family = AF_INET;
- local_addr.sin_port = htons(PORT);
- local_addr.sin_addr.s_addr = INADDR_ANY;
- bzero(&(local_addr.sin_zero), 8);
- if(bind(listensock, (struct sockaddr*)&local_addr, sizeof(struct sockaddr)) == -1)
- {
- cout << "bind error" << endl;
- exit(1);
- }
- else
- {
- cout << "bind success" << endl;
- }
- if(listen(listensock, BACKLOG) == -1)
- {
- cout << "listen error" << endl;
- exit(1);
- }
- else
- {
- cout << "listen success" << endl;
- }
- int addrlen = sizeof(struct sockaddr_in);
- if((clientsock = accept(listensock, (struct sockaddr*)&client_addr,(socklen_t*)&addrlen)) == -1)
- {
- cout << "accept error" << endl;
- exit(1);
- }
- else
- {
- cout << "accept success" << endl;
- }
- cout << "receive a connetion from Ip: " << inet_ntoa(client_addr.sin_addr) << " Port:" << ntohs(client_addr.sin_port) << endl;
- cout << "prepare send data" << endl;
- while(1)
- {
- cin >> buf;
- int sendlen = strlen(buf);
- if((send(clientsock, buf, sendlen, 0)) == -1)
- {
- cout << "send data error" << endl;
- }
- }
- close(clientsock);
- }
客户端:
- #include<stdio.h>
- #include<stdlib.h>
- #include<string.h>
- #include<errno.h>
- #include<sys/wait.h>
- #include<sys/socket.h>
- #include<sys/types.h>
- #include<netinet/in.h>
- #include<arpa/inet.h>
- #include<iostream>
- using namespace std;
- #define PORT 4002
- int main()
- {
- int sockfd;
- struct sockaddr_in serv_addr;
- char buf[1024];
- int recvlen;
- if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
- {
- cout << "socket create error" << endl;
- exit(1);
- }
- serv_addr.sin_family = AF_INET;
- serv_addr.sin_port = htons(PORT);
- serv_addr.sin_addr.s_addr = inet_addr("10.0.30.66");
- bzero(&(serv_addr.sin_zero), 8);
- if((connect(sockfd, (struct sockaddr*)&serv_addr, sizeof(struct sockaddr))) == -1)
- {
- cout << "connect error" << endl;
- exit(1);
- }
- cout << "prepare recv data" << endl;
- while(1)
- {
- if((recvlen = recv(sockfd, buf, sizeof(buf), 0)) == -1)
- {
- cout << "recv error" << endl;
- exit(1);
- }
- buf[recvlen] = '\0';
- cout << "received: " << buf << endl;
- }
- close(sockfd);
- }
阅读(2041) | 评论(0) | 转发(0) |