Copy of Socket Connection Using python

Recently, I worked on the socket connection using Python for bi-directional communication between client and server. So I have some basic idea about socket connection in easy ways

Socket Connection: Socket communication is a part of the computer network for communication between the client and server sides. Communication is done through the IP and port numbers of the server and client, both of which are bound to the same IP and port.

It works like a pipe line communication between end points If one communication established, no one interrupt the other. If anyone send another request for the communication from server, then it handles multithreaded and Async programming mechanisms. There are some methods used on the server side as well as client side

client:

import socket

client_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

Host = "127.0.0.1"
PORT = 62314

print("Waiting for connection")
try:
    client_socket.connect((Host, PORT))
except socket.error as e:
    print(str(e))

while True:
    Response = client_socket.recv(1024)
    print(Response.decode('utf-8'))
    Input = input("Say Something")
    client_socket.send(str.encode(Input))
    response = client_socket.recv(1024)
    print(response.decode("utf-8"))

client_socket.close()        

Server:

import socket
from _thread import *
import threading


server_socket= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Host = "127.0.0.1"
PORT = 62314
thread_count =0

try:
    server_socket.bind((Host,PORT))
except socket.error as e:
    print(str(e))
print("Waiting for connection")
server_socket.listen(10)


def client_thread(connection):
    connection.send(str.encode("Welcome to the Server"))
    while True:
        data = connection.recv(10240)
        reply = "Hello I'm Server" + data.decode("utf-8")
        if not data:
            break
        connection.sendall(str.encode(reply))
    connection.close()

while True:
    client, address = server_socket.accept()
    print("connected to" + address[0] + str(address[1]))
    threading.Thread(target=client_thread, args=(client,)).start()
    thread_count+=1
    print("Thread Number" + str(thread_count))
server_socket.close()        

要查看或添加评论,请登录

社区洞察

其他会员也浏览了