1. 程式人生 > >Winock客戶端和服務端程式碼

Winock客戶端和服務端程式碼

服務端:

#include "stdafx.h"
#include <iostream>
#include <winsock2.h>
#include <ws2tcpip.h>

using namespace std;
#pragma comment (lib,"WS2_32.lib")
int main()
{
	WSADATA wsaData;
	int nRst;
	nRst= WSAStartup(MAKEWORD(2,2),&wsaData);
	if (0 != nRst)
	{
		cout << "WSAStartup() error"
<< endl; return 1; } sockaddr_in servAddr; sockaddr_in clntAddr; char message[] = "hello world!"; SOCKET servSock = socket(AF_INET, SOCK_STREAM, 0); if (-1 == servSock) { cout << "sock() err" << endl; return 1; } memset(&servAddr, 0, sizeof(sockaddr_in)); servAddr.
sin_family = AF_INET; servAddr.sin_addr.s_addr = htonl(INADDR_ANY); servAddr.sin_port = htons(9008); if (-1 == bind(servSock,(sockaddr*)&servAddr,sizeof(sockaddr_in))) { cout << "bind() error" << endl; return 1; } if (-1 == listen(servSock,5)) { cout << "listen() error"
<< endl; } socklen_t clntAddrSize; clntAddrSize = sizeof(sockaddr_in); SOCKET clntSock = accept(servSock, (sockaddr*)&clntAddr, &clntAddrSize); if (-1==clntSock) { cout << "accept() error" << endl; } if (-1 == send(clntSock, message, sizeof(message), 0)) { cout << "send() error" << endl; return 1; } closesocket(clntSock); closesocket(servSock); WSACleanup(); system("pause"); return 0; }

客戶端:

#include "stdafx.h"
#include <iostream>
#include <winsock2.h>
using namespace std;

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

int main()
{
	WSADATA wsaData;
	WSAStartup(MAKEWORD(2, 2), &wsaData);
	SOCKET sock = socket(AF_INET,SOCK_STREAM,0);
	if (-1== sock)
	{
		cout << "socket() error" << endl;
		return 0;
	}

	sockaddr_in servAddr;
	memset(&servAddr, 0, sizeof(sockaddr_in));
	servAddr.sin_family = AF_INET;
	servAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
	servAddr.sin_port = htons(9008);

	if (connect(sock,(sockaddr*)&servAddr,sizeof(sockaddr_in))==-1)
	{
		cout << "connect() error" << endl;
	}

	char message[30] = {0};
	int strLen = recv(sock,message,sizeof(message)-1,0);
	if (-1 == strLen)
	{
		cout << "recv() error" << endl;
	}

	cout << "Get message from server ,the message is:" << message << endl;

	closesocket(sock);

	WSACleanup();

	system("pause");
    return 0;
}