TCP客戶度 服務端的簡單通訊方式

2021-09-25 17:03:12 字數 3161 閱讀 6821

01-tcp-client.py

import socket

def main():

# 1\建立tcp套接字

tcp_client_socket = socket.socket(socket.af_inet,socket.sock_stream)

# 2\鏈結伺服器

serve_ip = input("inpurt serve dest ip:")

serve_port = int(input("input serve dest port:"))

tcp_client_socket.connect((serve_ip,serve_port ))# 只要鏈結成功就可以傳送了

# 3\傳送資料

send_data = input("data:")

tcp_client_socket.send(send_data.encode("utf-8"))

# 4\關閉套接字

tcp_client_socket.close()

if __name__ == "__main__":

main()

02-tcp-server.py

import socket

def main():

# 1\建立套接字

tcp_server_socket = socket.socket(socket.af_inet,socket.sock_stream)

# 2\繫結ip和埠

tcp_server_socket.bind(("",8899))

# 3\監聽套接字

tcp_server_socket.listen(128)

print("-------------1------------------")

# 等待客戶端鏈結,acept

new_client_socket,client_addr = tcp_server_socket.accept()#預設堵塞,知道有新的陶傑子接受他

print("-------------2------------------")

print(client_addr)

# 接受客戶端傳送的請求

recv_data = new_client_socket.recv(1024)#預設堵塞 注意這裡返回的僅僅是資料,和udp通訊的recvfrom不一樣,那個返回元組

print(recv_data.decode("utf-8"))

# 答覆

new_client_socket.send("收到.".encode("utf-8"))

# 關閉陶傑子

new_client_socket.close()

tcp_server_socket.close()

if __name__=="__main__":

main()

import socket

def main():

# 1\建立套接字

tcp_socket = socket.socket(socket.af_inet,socket.sock_stream)

# 2\獲取伺服器的ip,port

# 3\鏈結伺服器

tcp_socket.connect((dest_ip,dest_port))

# 5\將檔案名字傳送給伺服器

tcp_socket.send(download_file_name.encode("utf-8"))

# 6\接受檔案中的資料

recv_data = tcp_socket.recv(1024*1024)# 1024是1k 1024*1024就是1m,1024*1024*1024=1g

if recv_data:

# 7\儲存接受到的資料到乙個檔案中

with open("[新]"+download_file_name,"wb") as file:#寫入二進位制的方式開啟

file.write(recv_data)

# 8\關閉套接字

tcp_socket.close()

if __name__=="__main__":

main()

import socket

def send_file_2_client(new_client_socket,client_addr):

file_name = new_client_socket.recv(1024)

file_content = none

# 2\開啟這個檔案,讀取資料

try:

f = open(file_name,"rb")

file_content = f.read()

f.close()

except exception as ret:

if(file_content):

# 3\傳送檔案的資料給客戶端

new_client_socket.send(file_content)

def main():

# 1\建立套接字

tcp_server_socket = socket.socket(socket.af_inet,socket.sock_stream)

# 2\繫結ip和埠

tcp_server_socket.bind(("",8800))

# 3\監聽套接字

tcp_server_socket.listen(128)

# 繼續為該客戶服務

while true:

# 4\等待客戶端鏈結,acept

new_client_socket,client_addr = tcp_server_socket.accept()#預設堵塞,知道有新的陶傑子接受他

# 5\傳送資料

TCP客戶端與服務端通訊

客戶端 include include include include include in.h include include include include define maxline 1024 int main int argc,char ar 建立socketfd socketfd soc...

TCP通訊,多客戶端通訊(客戶端 服務端)

客戶端和伺服器間的交流,客戶端傳送資訊,伺服器接收到,並返回資訊 長連線建立socket連線服務端 指定ip位址,埠號 通過ip位址找對應的伺服器 呼叫socket的getinputstream 和getoutputstream 方法獲取和服務端相連的io流 輸入流可以讀取服務端輸出流寫出的資料 輸...

TCP連線實現 客戶端 服務端 通訊

客戶端 client.c include include include include include include include include define max buf 512 int main int argc,char argv 設定伺服器位址結構體 bzero server ad...