SoFunction
Updated on 2024-10-30

Python3 socket instant messaging script implementation code example (threading multi-threading)

Python provides two levels of access to web services. :

Low-level network services support basic sockets, which provide the standard BSD Sockets API with access to the full methods of the underlying operating system's socket interface.

The high-level network service module, SocketServer, provides server-centric classes that simplify the development of network servers.

------------------------------------------------ server-side code --------------------------------------

__author__ = "Mr. Tony."

"""
Instant Messaging Principles
@@@ server-side code

"""

from socket import *
import threading

ip = '0.0.0.0'
port =8888
# Define socket parameters

Server = socket(AF_INET,SOCK_STREAM)
((ip,port))
()
print("[*] SocketServer is listening...")

# Accept function
def recvs():
  while 1:
    print(' [*] Client says: %s '% (1024).decode('utf-8'))

#Send function
def sends():
  while 1:
    say = bytes(input(' [*] I said: ') , encoding='utf-8')
    (say)
# Blocking acceptance requests

client,client_ip = ()
print(client_ip[0] +':'+str(client_ip[1])+' Connection successful!' )

# Create acceptance threads
receive = (target =recvs ,args=() )
()
# Create the sending thread
send = (target =sends ,args=() )
()

------------------------------------------------ client code --------------------------------------

__author__ = "Mr. Tony."

"""
Instant Messaging Principles
@@@ Client Code

"""

from socket import *
import threading

ip,port ='127.0.0.1',8888

Client = socket(AF_INET,SOCK_STREAM)
((ip,port))

def sends() -> 'Send function':
  while 1:

    say = bytes(input("[*] I said: "),encoding='utf-8')
    (say)
def recvs() -> 'Accept function':
  while 1:

    print('[*] The server says: %s ' % (1024).decode('utf-8'))

receive = (target =recvs ,args=() )
()
# Create the sending thread
send = (target =sends ,args=() )
()

Execute the server-side code first, and then execute the client-side code, you can realize the basic communication function.

This is the whole content of this article.