C/S

socket还不是太熟悉,首先要链接库文件

下面是简单的测试代码,可以运行,已经测试过^^.

S:

#include <iostream>

#include <winsock2.h>

#pragma comment(lib,"ws2_32.lib")



int main()

{

	SOCKET serversock,clientsock;

	WSADATA  wsa;

	char buf[100];

	struct sockaddr_in serveraddr;



	WSAStartup(MAKEWORD(2,2),&wsa);      



	serversock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);  //使用TCP协议

	serveraddr.sin_family=AF_INET;

	serveraddr.sin_port=htons(6666);

	serveraddr.sin_addr.S_un.S_addr=INADDR_ANY;  //自动获取本地IP地址



	bind(serversock,(struct sockaddr*)&serveraddr,sizeof(serveraddr));

	listen(serversock,1);

	



	clientsock=accept(serversock,NULL,NULL); //返回新的socket

	memset(buf,0,100);

	recv(clientsock,buf,100,0);      //接收客户端的信息

	strcat(buf,"  this is server");

	send(clientsock,buf,100,0);         //服务器发送信息

	closesocket(serversock);

	WSACleanup();                 //释放资源

	return 0;

}

 C:

#include <iostream>

#include <winsock2.h>

#pragma comment(lib,"ws2_32.lib")



using namespace std;



int main()

{

	SOCKET sockclient;

	struct sockaddr_in clientaddr;

	char buf[100]="I am a mouse";

	WSADATA wsa;



	WSAStartup(MAKEWORD(2,2),&wsa);             //初始化



	sockclient=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);          //使用TCP协议

	clientaddr.sin_family=AF_INET;

	clientaddr.sin_port=htons(6666);

	clientaddr.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");

	connect(sockclient,(struct sockaddr*)&clientaddr,sizeof(clientaddr));        //链接服务器



	send(sockclient,buf,100,0);                    //发送信息

	memset(buf,0,100);

	recv(sockclient,buf,100,0);                    //从客户端接收信息

	cout<<"buf:"<<buf<<endl;

	closesocket(sockclient);

	WSACleanup();                                  //释放资源

	system("pause");

	return 0;

}

 

你可能感兴趣的:(C/S)