熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

ASP.NET基於TCP的網絡通信程序演示

2022-06-13   來源: .NET編程 

  本程序僅僅是為了演示基於TCP協議TCP協議的網絡通信程序的寫法采用阻塞模式代碼簡單

  服務器端代碼

  #include Winsockh
#include stdioh

  void main()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;

  wVersionRequested = MAKEWORD();

  err = WSAStartup( wVersionRequested &wsaData );
if ( err != )
{
return;
}

  if ( LOBYTE( wsaDatawVersion ) != ||
HIBYTE( wsaDatawVersion ) != )
{
WSACleanup( );
return;
}

  SOCKET sockSrv=socket(AF_INETSOCK_STREAM);
SOCKADDR_IN addrSrv;
addrSrvsin_addrS_unS_addr=htonl(INADDR_ANY);
addrSrvsin_family=AF_INET;
addrSrvsin_port=htons();

  bind(sockSrv(SOCKADDR*)&addrSrvsizeof(SOCKADDR));

  listen(sockSrv);

  SOCKADDR_IN addrClient;
int len=sizeof(SOCKADDR);

  while()
{
SOCKET sockConn=accept(sockSrv(SOCKADDR*)&addrClient&len);

  char sendBuf[];

  sprintf(sendBufWelcom %s to inet_ntoa(addrClientsin_addr));
send(sockConnsendBufstrlen(sendBuf)+);

  char recvBuf[];
recv(sockConnrecvBufstrlen(recvBuf));
printf(%s\nrecvBuf);
closesocket(sockConn);
}
}

  『注意』本程序使用了動態連接庫文件Ws_lib需要在工程屬性裡添加對Ws_lib的連接本程序用VC編譯添加方法是在project\Configuration properties\Linker\Input下的Additional Dependencies 項裡寫如Ws_lib

  客戶端代碼

  #include Winsockh
#include stdioh

  void main()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;

  wVersionRequested = MAKEWORD();

  err = WSAStartup( wVersionRequested &wsaData );
if ( err != )
{
return;
}

  if ( LOBYTE( wsaDatawVersion ) != ||
HIBYTE( wsaDatawVersion ) != )
{
WSACleanup( );
return;
}

  SOCKET sockClient=socket(AF_INETSOCK_STREAM);
SOCKADDR_IN addrSrv;
addrSrvsin_addrS_unS_addr=inet_addr(); //

  一個回路地址
addrSrvsin_family=AF_INET;
addrSrvsin_port=htons();

  connect(sockClient(SOCKADDR*)&addrSrvsizeof(SOCKADDR));

  char recvBuf[];
recv(sockClientrecvBufstrlen(recvBuf));
printf(%s\nrecvBuf);
send(sockClient我是胡林strlen(我是胡林)+);
closesocket(sockClient);
WSACleanup();
}

  同服務器端一樣客戶端程序也使用了Ws_lib動態連接庫需要在工程屬性裡添加對Ws_lib的連接


From:http://tw.wingwit.com/Article/program/net/201311/13794.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.