程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python uses sockets to transmit data (TCP) from different computers in the same LAN

編輯:Python

This use tcp Protocol transfer data ( That is, set word selection tcp The corresponding parameter ,SOCKET_STREAM)

One 、 precondition :

          Import socket package , Two computers under one LAN ( Or create one locally win virtual machine )

Two 、 Create server

        1、 Create socket

        2、 Bind local information

        3、 Use listen Change the default socket from active to passive

        4、 Waiting for a link from the client (accept), And create a socket to serve the linked client

        5、 Receiving data from clients

        6、 Send data to client

        7、 Close socket

from socket import *
def main():
# Create socket , Listening socket Be responsible for waiting for the new client to link
tcp_server_socket = socket(AF_INET,SOCK_STREAM)
# Bind local information
tcp_server_socket.bind(('' ,7890))
# Change socket from active to passive
tcp_server_socket.listen(128)
print('-------------listen---------')
#accept Waiting for a link from the client accept The new socket generated is used to serve the client
client_scoket,client_addr = tcp_server_socket.accept()
print('-------------accept---------')
print(client_addr)
# Receive information from clients
recv_data=client_scoket.recv(1024)
print(recv_data.decode('utf-8'))
# Send messages to clients
client_scoket.send(' Ha ha ha ha '.encode('utf-8'))
# Close socket
client_scoket.close()
tcp_server_socket.close()
if __name__ == '__main__':
main()

        

3、 ... and 、 Create client

        1、 Create socket

        2、 Link server

        3、 send out / receive data

        4、 Close socket

from socket import *
def main():
# Create socket
tcp_clien_socket = socket(AF_INET, SOCK_STREAM)
# Link server
server_addr = ('192.168.25.234', 7890)
tcp_clien_socket.connect(server_addr)
# send out / receive data
send_data = input(' Please input the data to be sent ')
tcp_clien_socket.send(send_data.encode('utf-8'))
rs_data = tcp_clien_socket.recv(1024)
print(rs_data.decode('utf-8'))
# Close socket
tcp_clien_socket.close()
if __name__ == '__main__':
main()

Four 、 Be careful !!:

        accept and recv When there is no link or data received, it will cause function congestion !! Be similar to input, It's just input Waiting for you to enter data on the command line , and accept and recv It is waiting for the link and data of the client or server .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved