目錄
服務端:
用戶端:
用戶端第二種寫法:不使用inet_pton函數
#include <iostream>
#include <stdio.h>
#include <winsock2.h>
#include <Ws2tcpip.h>
#pragma comment(lib,"ws2_32.lib")
#define _WINSOCK_DEPRECATED_NO_WARNINGS 1
using namespace std;
int main(int argc, char* argv[])
{
//初始化WSA
WORD sockVersion = MAKEWORD(2, 2);
WSADATA wsaData;
if (WSAStartup(sockVersion, &wsaData) != 0)
{
return 0;
}
//建立套接字
SOCKET slisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (slisten == INVALID_SOCKET)
printf("socket error !");
//綁定IP和端口
sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(8888);
sin.sin_addr.S_un.S_addr = INADDR_ANY;
if (bind(slisten, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR)
printf("bind error !");
//開始監聽
if (listen(slisten, 5) == SOCKET_ERROR)
printf("listen error !");
//循環接收資料
SOCKET sClient;
sockaddr_in remoteAddr;
int nAddrlen = sizeof(remoteAddr);
char revData[255];
while (true)
printf("等待連接配接...\n");
sClient = accept(slisten, (SOCKADDR *)&remoteAddr, &nAddrlen);
if (sClient == INVALID_SOCKET)
{
printf("accept error !");
continue;
}
char ip[100];
if (inet_ntop(AF_INET, &remoteAddr.sin_addr.S_un.S_addr, ip, 100) == NULL)
cout << "error" << endl;
return -1;
cout << ip << endl; //寬字元記得用寬字元的方式進行輸出
//接收資料
int ret = recv(sClient, revData, 255, 0);
if (ret > 0)
revData[ret] = 0x00;
printf(revData);
//發送資料
const char * sendData = "你好,TCP用戶端!\n";
send(sClient, sendData, strlen(sendData), 0);
closesocket(sClient);
closesocket(slisten);
WSACleanup();
return 0;
}
#include<iostream>
#include<WINSOCK2.H>
#include<STDIO.H>
#include<cstring>
#pragma comment(lib, "ws2_32.lib")
int main()
WSADATA data;
if (WSAStartup(sockVersion, &data) != 0)
while (true) {
SOCKET sclient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sclient == INVALID_SOCKET)
printf("invalid socket!");
return 0;
sockaddr_in serAddr;
serAddr.sin_family = AF_INET;
serAddr.sin_port = htons(8888);
inet_pton(AF_INET, "127.0.0.1", &serAddr.sin_addr.S_un.S_addr);
if (connect(sclient, (sockaddr *)&serAddr, sizeof(serAddr)) == SOCKET_ERROR)
{ //連接配接失敗
printf("connect error !");
closesocket(sclient);
char data[1024];
cin >> data;
const char * sendData;
sendData = data; //string轉const char*
//char * sendData = "你好,TCP服務端,我是用戶端\n";
send(sclient, sendData, strlen(sendData), 0);
//send()用來将資料由指定的socket傳給對方主機
//int send(int s, const void * msg, int len, unsigned int flags)
//s為已建立好連接配接的socket,msg指向資料内容,len則為資料長度,參數flags一般設0
//成功則傳回實際傳送出去的字元數,失敗傳回-1,錯誤原因存于error
char recData[255];
int ret = recv(sclient, recData, 255, 0);
if (ret > 0) {
recData[ret] = 0x00;
printf(recData);
closesocket(sclient);
serAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");