可算Windows客戶端最簡單的例子了,看看吧。
//連接到服務器端(127.0.0.1)555端口上,發送字符串1234567過去,然後關閉連接,退出程序。
#include
<
windows.h
>
#include < stdio.h >
#pragma comment (lib, "WS2_32.lib")
#define DEFAULT_PORT 555
int main( void ) ... {
printf("開始... ");
//初始化
WSADATA wsd;
if(WSAStartup(MAKEWORD(2, 2), &wsd) != 0)...{
printf("WSAStartup error! ");
return FALSE;
}
SOCKET sSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
if(sSocket == SOCKET_ERROR)...{
printf("SOCKET ERROR! ");
return FALSE;
}
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_addr.s_addr = htonl(0x7f000001);//127.0.0.1
server.sin_port = htons(DEFAULT_PORT);
//連接
if(connect(sSocket, (struct sockaddr *)&server, sizeof(sockaddr_in)) == SOCKET_ERROR)...{
printf("連接失敗!(connect error!) ");
return FALSE;
}
printf("連接成功! ");
int ret = send(sSocket, "1234567", 7, 0);
if(ret == SOCKET_ERROR)...{
printf("send error! ");
return FALSE;
}else...{
printf("共發送%d字節數據! ", ret);
}
printf("結束! ");
//結束
closesocket(sSocket);
WSACleanup();
return TRUE;
}
#include < stdio.h >
#pragma comment (lib, "WS2_32.lib")
#define DEFAULT_PORT 555
int main( void ) ... {
printf("開始... ");
//初始化
WSADATA wsd;
if(WSAStartup(MAKEWORD(2, 2), &wsd) != 0)...{
printf("WSAStartup error! ");
return FALSE;
}
SOCKET sSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
if(sSocket == SOCKET_ERROR)...{
printf("SOCKET ERROR! ");
return FALSE;
}
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_addr.s_addr = htonl(0x7f000001);//127.0.0.1
server.sin_port = htons(DEFAULT_PORT);
//連接
if(connect(sSocket, (struct sockaddr *)&server, sizeof(sockaddr_in)) == SOCKET_ERROR)...{
printf("連接失敗!(connect error!) ");
return FALSE;
}
printf("連接成功! ");
int ret = send(sSocket, "1234567", 7, 0);
if(ret == SOCKET_ERROR)...{
printf("send error! ");
return FALSE;
}else...{
printf("共發送%d字節數據! ", ret);
}
printf("結束! ");
//結束
closesocket(sSocket);
WSACleanup();
return TRUE;
}
其服務器端詳見文章“視窗:網路-最簡示例(服務器端) ”或“視窗:網路-完成端口-最簡示例(服務器端) ”。