转:
http://blog.csdn.net/rangf/article/details/8315728
linux端:
-
#include
-
#include
-
#include
-
#include
-
#include
-
#include
-
#include
-
#include
-
#define MYPORT 3333
-
#define BACKLOG 10
-
main()
-
{
-
int sockfd, new_fd;
-
struct sockaddr_in my_addr;
-
struct sockaddr_in their_addr;
-
int sin_size;
-
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
-
perror("socket");
-
exit(1);
-
}
-
my_addr.sin_family = AF_INET;
-
my_addr.sin_port = htons(MYPORT);
-
my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
-
bzero(&(my_addr.sin_zero),0);
-
if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr))== -1) {
-
perror("bind");
-
exit(1);
-
}
-
if (listen(sockfd, BACKLOG) == -1) {
-
perror("listen");
-
exit(1);
-
}
-
while(1) {
-
sin_size = sizeof(struct sockaddr_in);
-
if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr,&sin_size)) == -1) {
-
perror("accept");
-
continue;
-
}
-
printf("server: got connection from %s\n",inet_ntoa(their_addr.sin_addr));
-
if (!fork()) {
-
if (send(new_fd, "Hello, world!\n", 14, 0) == -1)
-
perror("send");
-
close(new_fd);
-
exit(0);
-
}
-
close(new_fd);
-
while(waitpid(-1,NULL,WNOHANG) > 0);
-
}
-
}
window端:
-
-
-
-
#include "stdafx.h"
-
#include
-
-
-
#include
-
#pragma comment (lib,"WS2_32.lib")
-
-
#include
-
-
-
int _tmain(int argc, _TCHAR* argv[])
-
{
-
int i;
-
char recvBuffer[255];
-
WORD wVersionRequested;
-
WSADATA wsaData;
-
-
int err;
-
wsaData.wVersion =MAKEWORD(1,1);
-
-
-
err=WSAStartup(wVersionRequested,&wsaData);
-
if(err!=0){
-
printf("Call WSAStart ERROR!");
-
exit(1);
-
}
-
-
-
-
-
-
-
SOCKET SocketClient=socket(AF_INET,SOCK_STREAM,0);
-
-
SOCKADDR_IN addrSrv;
-
-
addrSrv.sin_addr.S_un.S_addr=inet_addr("172.17.51.81");
-
addrSrv.sin_family=AF_INET;
-
addrSrv.sin_port=htons(3333);
-
printf("Connect to server...\n");
-
i=connect(SocketClient,(sockaddr *)&addrSrv,sizeof(SOCKADDR_IN));
-
if(i<0){
-
printf("%i\n",WSAGetLastError());
-
printf("连接到172.17.51.81:3333错误!");
-
exit(1);
-
}
-
recv(SocketClient,recvBuffer,255,0);
-
printf("%s\n",recvBuffer);
-
closesocket(SocketClient);
-
WSACleanup();
-
return 0;
-
}
注:
1、windows下控制台程序,需要注意加链接库ws2_32.lib
2、文件名以cpp结尾,解决SOCKET等符号找不到问题
3、#include 解决exit符号找不到问题
4、补充第1点:#pragma comment (lib,"WS2_32.lib")
阅读(5853) | 评论(0) | 转发(1) |