Home > Backend Development > Python Tutorial > Detailed introduction of python Socket client and server handshake

Detailed introduction of python Socket client and server handshake

巴扎黑
Release: 2017-09-21 10:55:13
Original
1684 people have browsed it

This article mainly introduces the client and server handshake of python Socket in detail. It has certain reference value. Interested friends can refer to

to learn how to use socket simply. Establish a connection between the client and the server and send data

1. Client socketClient.py code


import socket 
 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
# 建立连接: 
s.connect(('127.0.0.1', 9999)) 
# 接收欢迎消息: 
print(s.recv(1024).decode('utf-8')) 
for data in [b'Michael', b'Tracy', b'Sarah']: 
 # 发送数据: 
 s.send(data) 
 print(s.recv(1024).decode('utf-8')) 
s.send(b'exit') 
s.close()
Copy after login

2. Server serverSocket.py Code


import socket 
import threading 
import time 
# from threading import Thread 
 
 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
# 监听端口: 
s.bind(('127.0.0.1', 9999)) 
s.listen(5) 
print('Waiting for connection...') 
 
def tcplink(sock, addr): 
 print('Accept new connection from %s:%s...' % addr) 
 sock.send(b'Welcome!') 
 while True: 
  data = sock.recv(1024) 
  time.sleep(1) 
  if not data or data.decode('utf-8') == 'exit': 
   break 
  sock.send(('Hello, %s!' % data.decode('utf-8')).encode('utf-8')) 
 sock.close() 
 print('Connection from %s:%s closed.' % addr) 
 
while True: 
 # 接受一个新连接: 
 sock, addr = s.accept() 
 # 创建新线程来处理TCP连接: 
 t = threading.Thread(target=tcplink, args=(sock, addr)) 
 t.start()
Copy after login

3. Operation process

Open two console windows, first run the server python3 serverSocket.py

and then run Client python3 socketClient.py

socket connection screenshot is as follows

The above is the detailed content of Detailed introduction of python Socket client and server handshake. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template