Example of handshake between client and server of Socket in python

黄舟
Release: 2017-09-18 11:36:02
Original
1976 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 Example of handshake between client and server of Socket in python. 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