Python implements a simple example of instant messaging based on socket

  • 2020-07-21 08:44:57
  • OfStack

This article illustrates Python's simple instant messaging based on socket. To share for your reference, specific as follows:

The client tcpclient py


# -*- coding: utf-8 -*-
import socket
import threading
#  The target address IP/URL And the port 
target_host = "127.0.0.1"
target_port = 9999
#  create 1 a socket object 
client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#  Connection between a host 
client.connect((target_host,target_port))
def handle_send():
  while True:
    content = raw_input()
    client.send(content)
def handle_receive():
  while True:
    response = client.recv(4096)
    print response
send_handler = threading.Thread(target=handle_send,args=())
send_handler.start()
receive_handler = threading.Thread(target=handle_receive,args=())
receive_handler.start()

Server-side tcpserver.py


# -*- coding: utf-8 -*-
import socket
import threading
#  Listen to the IP And the port 
bind_ip = "127.0.0.1"
bind_port = 9999
#socket  Server initialization 
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.bind((bind_ip,bind_port))
server.listen(5)
print "[*] Listening on %s:%d" % (bind_ip,bind_port)
#  Define a function handle_client, The input parameters client_socket
def handle_client():
  while True:
    request = client_socket.recv(1024)
    print "[*] Received:%s" % request
def handle_send():
  while True:
    content = raw_input()
    client_socket.send(content);
# Blocking here, waiting to receive data from the client 
client_socket,addr = server.accept()
print "[*] Accept connection from:%s:%d" % (addr[0],addr[1])
# create 1 A thread 
client_handler = threading.Thread(target=handle_client,args=())
client_handler.start()
send_handler = threading.Thread(target=handle_send,args=())
send_handler.start()

For more information about Python, please visit Python Socket Programming Skills summary, Python Data Structure and Algorithm Tutorial, Python Function Usage Skills Summary, Python String Manipulation Skills Summary, Python Introduction and Advanced Classic Tutorial and Python File and Directory Manipulation Skills Summary.

I hope this article has been helpful in Python programming.


Related articles: