SoFunction
Updated on 2024-07-15

Client-server handshaking with python Socket

Simply learn how to use sockets to establish a connection between a client and a server and send data.

1. Client code

import socket 
 
s = (socket.AF_INET, socket.SOCK_STREAM) 
# Connections established.
(('127.0.0.1', 9999)) 
# Receive a welcome message.
print((1024).decode('utf-8')) 
for data in [b'Michael', b'Tracy', b'Sarah']: 
 # Send data.
 (data) 
 print((1024).decode('utf-8')) 
(b'exit') 
() 

2. Server-side code

import socket 
import threading 
import time 
# from threading import Thread 
 
 
s = (socket.AF_INET, socket.SOCK_STREAM) 
# Listener ports.
(('127.0.0.1', 9999)) 
(5) 
print('Waiting for connection...') 
 
def tcplink(sock, addr): 
 print('Accept new connection from %s:%s...' % addr) 
 (b'Welcome!') 
 while True: 
  data = (1024) 
  (1) 
  if not data or ('utf-8') == 'exit': 
   break 
  (('Hello, %s!' % ('utf-8')).encode('utf-8')) 
 () 
 print('Connection from %s:%s closed.' % addr) 
 
while True: 
 # Accept a new connection: #
 sock, addr = () 
 # Create a new thread to handle TCP connections.
 t = (target=tcplink, args=(sock, addr)) 
 () 

3. Operation process

Open two console windows and run the server side first python3

Then run the client python3

A screenshot of the socket connection is shown below

This is the whole content of this article.