日期:2014-05-17  浏览次数:20710 次

windows下TCP通讯

客户端

#include <iostream>
#include <Windows.h>
#include <Winsock.h>
using namespace std;

int main()
{
	//客户端
    WSAData wsad;
    WSAStartup(MAKEWORD(2,2),&wsad);

	// 创建socket
    SOCKET cli = socket(AF_INET,SOCK_STREAM,0);

	// 创建含有服务器地址的数据结构
    SOCKADDR_IN ser_addr;
    ser_addr.sin_family = AF_INET;
    ser_addr.sin_addr.s_addr = inet_addr("10.15.1.218");
    ser_addr.sin_port = htons(7654);

	// 连接服务器
	int res = connect(cli, (sockaddr*)&ser_addr, sizeof(SOCKADDR_IN));
	if (res != 0)
	{
		cout<<"connect error, return "<<connRes<<endl;
	}

	cout<<"connect success!"<<endl;

	// 发送数据
    char buf[] = "hello";
    send(cli, buf, sizeof(buf), 0);
    WSACleanup();

	while (1)
	{
		Sleep(5);
	}
	return 0;
}


?

?