TCP服務端傳送資料(C )

2021-10-05 18:16:32 字數 1468 閱讀 2682

本文記錄c++實現tcp協議的服務端部分,注意文中的阻塞態會長期存在,知道客戶端響應為止。

#include

"pch.h"

#include

#include

#pragma comment(lib,"ws2_32.lib")

using

namespace std;

intmain

(int argc,

char

* ar**)

//建立套接字

socket slisten =

socket

(af_inet, sock_stream, ipproto_tcp);if

(slisten == invalid_socket)

//繫結主機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)if(

listen

(slisten,5)

== socket_error)

//迴圈接收資料

socket sclient;

sockaddr_in remoteaddr;

int naddrlen =

sizeof

(remoteaddr)

;char revdata[

255]

;while

(true)

cout <<

"接入連線:"

<<

inet_ntoa

(remoteaddr.sin_addr)

<< endl;

//接收資料

int ret =

recv

(sclient, revdata,

255,0)

;if(ret >0)

//傳送資料

const

char

* senddata =

"hello tcp!\n"

;send

(sclient, senddata,

strlen

(senddata),0

);closesocket

(sclient);}

closesocket

(slisten)

;wsacleanup()

;return0;

}

python使用TCP服務端傳送接受資料

import socket 建立套接字 tcp server socket socket.socket socket.af inet,socket.sock stream 繫結本地資訊 tcp server socket.bind 7890 listen 監聽 tcp server socket.l...

TCP服務端實現併發

socket 在 tcp 協議下通訊 客戶端import socket 建立客戶端tcp協議通訊 c socket.socket 與指定服務端握手 c.connect 127.0.0.1 8080 通訊迴圈 while true 向服務端傳送資訊 msg input if len msg 0 con...

TCP客戶端服務端demo

服務端程式 include include include include include include include int main 列印握手成功的客戶端 struct sockaddr in servaddr socklen t nservlen sizeof servaddr getso...