linuxä¸çç¨åºå¦ä½å¨windowsä¸è¿è¡
æ¬è´¨åºå«æ¯è¿æ ·çï¼linuxä¸ç¨çæ¯ä¼¯å å©socketï¼windowsåºä¸ç¨çWinSocket.
两è å ¶å®æ¯å¤§åå°å¼çï¼ä¸åçå°æ¹å¨ä»¥ä¸å ç¹ï¼
1 头æ件ä¸åï¼å¨linuxä¸ç¨å°çå ³é®å¤´æ件<sys/socket.h>
windowsä¸ç¨å°çæ¯ <Winsock2.h>
2 socketçåå§åä¸ä¸æ ·ï¼å¨windowsä¸è¦æä¸ä¸ªWSAStartupï¼èlinux ä¸æ²¡æã
3 å ·ä½çç»èä¸ä¸æ ·ï¼linuxä¸çcåwindowsä¸çcçä¸äºè¯æ³æäºåºå ¥ï¼ä½ èªå·±æ¾æ¾ã
ä¸é¢ææwindowsä¸çsocketé讯çæåºæ¬çç»æç»ä½ ï¼ä½ å¯¹ç §çä¿®æ¹å°±å¯ä»¥äºï¼ä¸ä¸çç¨åºæè°è¯äºä¸ä¸ï¼ç¼è¯è¿äºã
客æ·ç«¯
#include <Winsock2.h>
#include <stdio.h>
void main()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 1,源码tomcat方法源码下载 1 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
return;
}
if ( LOBYTE( wsaData.wVersion ) != 1 ||
HIBYTE( wsaData.wVersion ) != 1 ) {
WSACleanup( );
return;
}
SOCKET sockClient=socket(AF_INET,SOCK_STREAM,0);
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr=inet_addr(".0.0.1");
addrSrv.sin_family=AF_INET;
addrSrv.sin_port=htons();
connect(sockClient,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
char recvBuf[];
recv(sockClient,recvBuf,,0);
printf("%s\n",recvBuf);
send(sockClient,"This is lisi",strlen("This is lisi")+1,0);
closesocket(sockClient);
WSACleanup();
}
æå¡å¨ç«¯
#include <Winsock2.h>
#include <stdio.h>
void main()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 1, 1 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
return;
}
if ( LOBYTE( wsaData.wVersion ) != 1 ||
HIBYTE( wsaData.wVersion ) != 1 ) {
WSACleanup( );
return;
}
SOCKET sockSrv=socket(AF_INET,SOCK_STREAM,0);
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
addrSrv.sin_family=AF_INET;
addrSrv.sin_port=htons();
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[];
sprintf(sendBuf,"æ¥èªæå¡å¨ç«¯",
inet_ntoa(addrClient.sin_addr));
send(sockConn,sendBuf,strlen(sendBuf)+1,0);
char recvBuf[];
recv(sockConn,recvBuf,,0);
printf("%s\n",recvBuf);
closesocket(sockConn);
}
}
2024-11-23 06:42
2024-11-23 06:38
2024-11-23 06:36
2024-11-23 06:21
2024-11-23 06:09