----------------------------------------------------------------------------
************************Tcp_client.cpp************************
----------------------------------------------------------------------------
#include
#include "WinSock2.h"
#pragma comment(lib,"ws2_32.lib")
SOCKET tcp_socket;
SOCKADDR_IN tcpAddr;
const int BufLen=1024;
char SendBuf[BufLen];
int main(int argc,char* argv[])
{
WSADATA wsd;
long int Addr;
int Port;
if(argc!=3){printf("Usage:%s [
Addr=inet_addr(argv[1]);
Port=atoi(argv[2]);
WSAStartup(MAKEWORD(2,2),&wsd);
tcp_socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
printf("Running in client mode(TCP)...\n");
tcpAddr.sin_family=AF_INET;
tcpAddr.sin_port=htons(Port);
tcpAddr.sin_addr.s_addr=Addr;
connect(tcp_socket,(LPSOCKADDR)&tcpAddr,sizeof(tcpAddr));
while (1)
{
ZeroMemory(SendBuf,BufLen);
fgets(SendBuf,BufLen,stdin);/*
gets_s(SendBuf,BufLen);
strcpy(SendBuf+strlen(SendBuf),"\n");*/
send(tcp_socket,SendBuf,BufLen,0);
}
closesocket(tcp_socket);
WSACleanup(); //释放套接字资源;
return 1;
}
----------------------------------------------------------------------------
***********************Tcp_service.cpp***********************
----------------------------------------------------------------------------
#include
#include "winsock2.h"
#pragma comment(lib,"ws2_32.lib")
SOCKET tcp_service_socket=INVALID_SOCKET;
SOCKADDR_IN tcpServiceAddr;
const int BufLen=1024;
char RecvBuf[BufLen];
SOCKET tcp_client_socket=INVALID_SOCKET;
SOCKADDR_IN tcpClientAddr;
int main()
{
WSADATA wsd;
int Port=8000;
WSAStartup(MAKEWORD(2,2),&wsd);
tcp_service_socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
tcpServiceAddr.sin_family=AF_INET;
tcpServiceAddr.sin_port=htons(Port);
printf("Running in service mode(TCP)...\n");
bind(tcp_service_socket,(LPSOCKADDR)&tcpServiceAddr,sizeof(tcpServiceAddr));
listen(tcp_service_socket,1);
int size=sizeof(tcpClientAddr);
tcp_client_socket=accept(tcp_service_socket,(sockaddr FAR*)&tcpClientAddr,&size);
while (1)
{
/* if (tcp_client_socket==INVALID_SOCKET)
{
Sleep(1000);
continue;
}*/
recv(tcp_client_socket,RecvBuf,BufLen,0);
printf("Received:%s\n",RecvBuf);
}
closesocket(tcp_client_socket);
closesocket(tcp_service_socket);
WSACleanup(); //释放套接字资源
return 1;
}
【点评】这是一个非常粗糙的例子,在实际应用中还需要做很多修改。