以下是tcp编程的两段代码,一段作为服务器,一段作为客户端,只要客户端打开新的程序,服务器端就能进行接收了。两个程序为在同一台机器上运行。
服务端
// w32_1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <winsock2.h>
#include <stdio.h>
#include <stdlib.h>
#define DEFAULT_PORT 5050
int _tmain(int argc, _TCHAR* argv[])
{
//initialize the Winsock
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if(iResult != NO_ERROR)
{
printf("Error at WSAStartup");
return 1;
}
//Create a socket for listening for
//incoming connection requests;
SOCKET socketListen;
socketListen = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(socketListen == INVALID_SOCKET)
{
printf("Error at socket():%ld/n",WSAGetLastError());
WSACleanup();
//这里之所以要清理,是因为上面WSAStartup()已经调入了winsock
return 1;
}
//接下来应该绑定端口,但在此之前,先要搞一个sockaddr_in结构放端口之类的信息
//The sockaddr_in structure specifies the address family,
//IP address, and port for the socket that is being bound.
sockaddr_in service;
service.sin_family = AF_INET;
service.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
//inet_addr
service.sin_port = htons(27015);
if(bind(socketListen, (sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
//sockaddr 根据协议不同会不同,所以需要转换一下
{
printf("bind() failed./n");
closesocket(socketListen);
//last step has created socket
WSACleanup();
return 1;
}
//绑定完成后,作为服务端接下来的工作就是监听了
//Listen for incomming connection requests.
//on the created socket
if(listen(socketListen, 1) == SOCKET_ERROR)
{
printf("listen() failed:%d",WSAGetLastError());
closesocket(socketListen);
WSACleanup();
return 1;
}
//server listen socket建立了,但是这是主socket,仅负责监听端口的功能
//要能接下来处理网络数据,我们需要再新建端口来完成
//Create a socket for accepting incoming requests.
SOCKET socketAccept;
while(1)
{
printf("waiting for client to connect.../n");
//accept the connection
socketAccept = accept(socketListen, NULL, NULL);
if(socketAccept == INVALID_SOCKET)
{
printf("accept failed:%d/n", WSAGetLastError());
closesocket(socketListen);
WSACleanup();
return 1;
}
else
{
printf("client connected/n");
}
closesocket(socketAccept);
//释放本次的链接
}
//no longer need server soket
closesocket(socketListen);
WSACleanup();
return 0;
}
//客户端
#include "stdafx.h"
#include <WinSock2.h>
#include <stdio.h>
#include <stdlib.h>
int _tmain(int argc, _TCHAR* argv[])
{
//同样测试协议,加载模块
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if(iResult != NO_ERROR)
{
printf("Error at WSAStartup");
return 1;
}
//同样创建socket
SOCKET socketConnection;
socketConnection = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(socketConnection == INVALID_SOCKET)
{
printf("Error at socket():%ld/n", WSAGetLastError());
WSACleanup();
//同样卸载模块资源
return 1;
}
//定义一个服务器地址
sockaddr_in service;
service.sin_family = AF_INET;
service.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
service.sin_port = htons(27015);
//接下来链接到服务器就行了
if(connect(socketConnection, (sockaddr*)&service, sizeof(service)) != 0)
{
printf("Error at connect:%ld", WSAGetLastError());
closesocket(socketConnection);
WSACleanup();
return 1;
}
return 0;
}