Sunday, 26 August 2018

Create messaging system in python using socket programming

I am new to socket programming. I wanted to create a simple messaging system between the server and the client ( chat ). I have included my code below. I am expecting it to work as similar as chat system but it doesn't work. If the message is sent it should receive and print it out but only after giving the input the received string is printed. I am expecting it should run parallelly (receive a message and send a message).

Server :

import socket
import time
import threading

def get(s):
    tm = s.recv(1024)
    print("\nReceived: ",tm.decode('ascii'))

def set_(s):
    i=input("\nEnter : ")
    s.send(i.encode('ascii'))

 serversocket = socket.socket()
 host = socket.gethostname()
 port = 9981
 serversocket.bind((host,port))
 serversocket.listen(1)
 clientsocket,addr = serversocket.accept()
 while(1):
    t1=threading.Thread( target = get ,  args = (clientsocket,) )
    t1.start()
    t2=threading.Thread( target = set_ ,  args = (clientsocket,) )
    t2.start()
    time.sleep(10)
clientsocket.close()

Client:

import socket
import threading
import time
def get(s):
    tm = s.recv(1024)
    print("\nReceived: ",tm.decode('ascii'))    

def set_(s):
    i=input("\nEnter : ")
    s.send(i.encode('ascii'))

s = socket.socket()
host = socket.gethostname()
port = 9981
s.connect((host,port))

while(1):
    t1=threading.Thread( target = get ,  args = (s,) )
    t2=threading.Thread( target = set_ , args = (s,) )
    t1.start()
    t2.start()
    time.sleep(10)
s.close()

Output (At Client) :

Enter: hello ------------------------------>(1)

Received: hello --------------------------->(3)

Output (At Server) :

Enter: hello ------------------------------>(2)

Received :  hello ------------------------->(4)

Expected Output:

Output (At Client) :

Enter: hello ------------------------------>(1)

Received: hello --------------------------->(4)

Output (At Server) :

Received :  hello ------------------------->(2)

Enter: hello ------------------------------>(3)

The number represents the order of execution.



from Create messaging system in python using socket programming

No comments:

Post a Comment