Tcp SOCKET 编程

客户端::::

#include <Winsock2.h>

#include <stdio.h>


void main()
{
//加载套接字库
WORD wVersionRequested;
WSADATA wsaData;
int err;

wVersionRequested = MAKEWORD( 1, 1 );//请求一个1.1的版本的Winsocket库

err = WSAStartup( wVersionRequested, &wsaData );//1、加载套接字库,2、确定使用哪一个套接字的版本库
if ( err != 0 ) { 
return;
}


if ( LOBYTE( wsaData.wVersion ) != 1 ||
        HIBYTE( wsaData.wVersion ) != 1 ) {
WSACleanup( );//终止对weinsocket库的使用
return; 
}
SOCKET sockClient=socket(AF_INET,SOCK_STREAM,0);
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");//服务器端的IP地址,本地回路地址(一台),不管有没有网卡都可以,用于测试
    addrSrv.sin_family=AF_INET;
addrSrv.sin_port=htons(6000);
connect(sockClient,(SOCKADDR *)&addrSrv,sizeof(SOCKADDR));
char recvBuf[100];
recv(sockClient,recvBuf,100,0);
printf("%s\n",recvBuf);
send(sockClient,"This is zhangsan",strlen("This is zhangsan")+1,0);
closesocket(sockClient);
WSACleanup();


}

服务端:::::

#include <Winsock2.h>
#include <stdio.h>


void main()
{
//加载套接字库
WORD wVersionRequested;
WSADATA wsaData;
int err;

wVersionRequested = MAKEWORD( 1, 1 );//请求一个1.1的版本的Winsocket库

err = WSAStartup( wVersionRequested, &wsaData );//1、加载套接字库,2、确定使用哪一个套接字的版本库
if ( err != 0 ) { 
return;
}


if ( LOBYTE( wsaData.wVersion ) != 1 ||
        HIBYTE( wsaData.wVersion ) != 1 ) {
WSACleanup( );//终止对weinsocket库的使用
return; 
}
//到此加载完库
//创建套接字
    SOCKET sockSrv=socket(AF_INET,SOCK_STREAM,0);//服务器端的套接字
//绑定套接字到地址和端口上
    SOCKADDR_IN addrSrv;
    addrSrv.sin_addr.S_un.S_addr=htonl(INADDR_ANY);//
/*htonl
       The htonl function converts a u_long from host to TCP/IP network byte order (which is big-endian).


       u_long htonl(
          u_long hostlong  );*/
    addrSrv.sin_family=AF_INET;
    addrSrv.sin_port=htons(6000);//只能用1024以上
bind(sockSrv,(SOCKADDR *)&addrSrv,sizeof(SOCKADDR));
    listen(sockSrv,5);
SOCKADDR_IN addrClient;
int len=sizeof(SOCKADDR);
while(1)
{
        SOCKET sockConn=accept(sockSrv,(SOCKADDR *)&addrClient,&len);
char sendBuf[100];
sprintf(sendBuf,"welcom %s to http://www.sunxin.org",inet_ntoa(addrClient.sin_addr));
send(sockConn,sendBuf,strlen(sendBuf)+1,0);
char recvBuf[100];
recv(sockConn,recvBuf,100,0);
printf("%s\n",recvBuf);
closesocket(sockConn);
}
}

注释::进一步完善中...

intWSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData);

wVersionRequested

[in] Highest version of Windows Sockets support that the caller can use.The high-order byte specifies the minor version (revision) number; thelow-order byte specifies the major version number.

lpWSAData

[out] Pointer to the WSADATAdata structure that is to receive details of the Windows Socketsimplementation.

 

typedef structWSAData {

  WORD                  wVersion;

  WORD                  wHighVersion;

  char                  szDescription[WSADESCRIPTION_LEN+1];

  char                 szSystemStatus[WSASYS_STATUS_LEN+1];

  unsigned short        iMaxSockets;

  unsigned short        iMaxUdpDg;

  char FAR *            lpVendorInfo;

} WSADATA,*LPWSADATA;

Members

wVersion

Version of the Windows Socketsspecification that the Ws2_32.dll expects the caller to use.

wHighVersion

Highest version of the Windows Socketsspecification that this .dll can support (also encoded as above). Normally thisis the same as wVersion.

szDescription

Null-terminated ASCII string into which theWs2_32.dll copies a description of the Windows Sockets implementation. The text(up to 256 characters in length) can contain any characters except control andformatting characters: the most likely use that an application can put this tois to display it (possibly truncated) in a status message.

szSystemStatus

Null-terminated ASCII string into which theWSs2_32.dll copies relevant status or configuration information. The Ws2_32.dllshould use this parameter only if the information might be useful to the useror support staff: it should not be considered as an extension of the szDescriptionparameter.

iMaxSockets

Retained for backward compatibility, butshould be ignored for Windows Sockets version 2 and later, as no single valuecan be appropriate for all underlying service providers.

iMaxUdpDg

Ignored for Windows Sockets version 2 andonward. iMaxUdpDg is retained for compatibility with Windows Socketsspecification 1.1, but should not be used when developing new applications. Forthe actual maximum message size specific to a particular Windows Socketsservice provider and socket type, applications should use getsockoptto retrieve the value of option SO_MAX_MSG_SIZE after a socket has beencreated.

lpVendorInfo

Ignored for Windows Sockets version 2 andonward. It is retained for compatibility with Windows Sockets specification1.1. Applications needing to access vendor-specific configuration informationshould use getsockopt to retrieve the value of option PVD_CONFIG.The definition of this value (if utilized) is beyond the scope of thisspecification.

 

SOCKET socket(

 int af,      

 int type,    

 int protocol 

);

af

[in] Address family specification. 指定地址族,对于TCP/IP协议的套接字,只能是AF_INET(PF_INET)

type

[in] Type specification for the new socket.指定Stocket类型,对于1.1版本的Stocket,只支持两种类型,SOCK_STREAM指定产生流式套接字,SOCK_DGRAM产生数据报套接字

protocol

[in] Protocol to be used with the socket that is specific to theindicated address family.

   与特定的地址家族相关的协议0 根据地址格式和套接字类别自动选择一个合适的协议

若调用成功,返回一个新的SOCKET数据类型的套接字描述符。若失败则返回INVALID_SOCKET,错误信息可以通过WSNGetLastError函数返回。

 

int bind(

 SOCKET s,                         

 const struct sockaddr FAR *name,  

 int namelen                       

);

Parameters

s

[in] Descriptor identifying an unbound socket. 指定要绑定的套接字

name

[in] Address to assign to the socket from the SOCKADDRstructure. 指定该套接字的本地地址信息,是指向sockaddr结构的指针变量,由于改地址结构是为所有地址家族准备的,这个结构可能随所用的网络协议不同而不同,所以要用第三个参数指定改地址结构的长度。

namelen

[in] Length of the value in the name parameter.

struct sockaddr {

 u_short    sa_family;指定改地址家族,必须设为AF_INET

 char       sa_data[14];表示要求一块内存分片区

}; 

可以用下面结构替代

struct sockaddr_in {

       short   sin_family;

       u_short sin_port;

       struct  in_addr sin_addr;

       char    sin_zero[8];

};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yzs87

你的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值