This use tcp Protocol transfer data ( That is, set word selection tcp The corresponding parameter ,SOCKET_STREAM)
Import socket package , Two computers under one LAN ( Or create one locally win virtual machine )
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()
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()