How to send json data ver a socket in python - python-3.x

I want to send a json data to client with json values taken from variables.
Please help to suggest how I can achieve this?
I have tried below code on server side but it does not work
# next create a socket object
s = socket.socket()
print("Socket successfully created")
s.bind(('', port))
print("socket binded to %s" % (port))
# put the socket into listening mode
s.listen(5)
print("socket is listening")
message = {'studentname': 'name', 'studentmark': 'marks'}
s,addr = s.accept()
while True:
tmp = s.recv(1024)
message += tmp
d = json.loads(message)
s.send(d)
print(d)

Related

be maked Infinite loop in python.3

i want to make one server and client in the python.3
this is my server:
import socket
ip =('192.168.1.101',12345)
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(ip)
s.listen(1)
print('Server is ready')
client , addr = s.accept()
print('one client has conected to me'+str(addr))
while True:
a = input('what do you want to tell ? ')
if a == 'q':
break
a=a.encode('utf_8')
client.sendall(a)
client.close()
and my client is :
import socket
ip = ('192.168.1.101', 12345)
conecttion = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
conecttion.connect(ip)
while True:
data = conecttion.recv(1024)
if data == 'q':
break
print(data)
conecttion.close()
but when i send 'q' in the client be maked Infinite loop.
what should i to do when i send 'q' the conection be closed.
who can help me.
Two issues:
On the server, you are not sending 'q'. You are breaking before the send.
On the client, the received data is binary so you need to convert to a character.
Try this code:
Server:
import socket
ip =('127.0.0.1',12345) # local machine
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(ip)
s.listen(1)
print('Server is ready')
client , addr = s.accept()
print('one client has conected to me'+str(addr))
while True:
a = input('what do you want to tell ? ')
aa=a.encode('utf_8')
client.sendall(aa) # byte data
if a == 'q': # original string
break
client.close()
Client:
import socket, time
ip = ('127.0.0.1', 12345) # local machine
conecttion = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
conecttion.connect(ip)
while True:
data = conecttion.recv(1024)
if data and chr(data[0]) == 'q':
break
print(data)
conecttion.close()

Why isnt my python socket server receiving the messages?

so i am making a chatroom in python using sockets for practice. I have made the server code using threading so that i can have more clients. Ive also made the client code, and when i try to run two clients at once so that they message from one to another, they connect to server, but the server doesnt seem to be receiving the message sent from either of the clients.
SERVER CODE:
import select
from threading import *
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# takes the first argument from command prompt as IP address
IP_address = "127.0.0.1"
# takes second argument from command prompt as port number
Port = int("50204")
server.bind((IP_address, Port))
server.listen(1000)
list_of_clients = []
def clientthread(conn, addr):
# sends a message to the client whose user object is conn
conn.send("Welcome to this chatroom!")
while True:
try:
message = conn.recv(4096)
if message:
print("<" + addr[0] + "> " + message.decode("UTF-8"))
# Calls broadcast function to send message to all
message_to_send = "<" + addr[0] + "> " + message
broadcast(message_to_send.encode("UTF-8"), conn)
else:
remove(conn)
except:
continue
def broadcast(message, connection):
for clients in list_of_clients:
if clients != connection:
try:
clients.send(message)
except:
clients.close()
# if the link is broken, we remove the client
remove(clients)
def remove(connection):
if connection in list_of_clients:
list_of_clients.remove(connection)
while True:
conn, addr = server.accept()
list_of_clients.append(conn)
# prints the address of the user that just connected
print(addr[0] + " connected")
# creates and individual thread for every user
# that connects
Thread(target=clientthread, args=(conn, addr))
conn.close()
server.close()
CLIENT CODE:
import socket
import sys
import time
class client:
def __init__(self):
self.server_ip = "127.0.0.1"
self.port = 50204
self.s = self.connect()
def connect(self):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print("Failed to create socket.")
sys.exit()
print("Socket created")
try:
s.connect((self.server_ip, self.port))
except socket.error:
print("Failed to connect to ip " + self.server_ip)
print("Connected to: " + str(s.getsockname()))
return s
def SocketQuery(self, Sock, cmd):
try:
try:
# Send cmd string
Sock.send(cmd)
print("Sent!")
time.sleep(1)
except socket.error:
# Send failed
print("Send failed!")
sys.exit()
reply = Sock.recv(4096)
return reply
except ConnectionResetError:
print("Server is down!")
def SocketClose(self, Sock):
# close the socket
Sock.close()
time.sleep(.300)
if __name__ == "__main__":
c = client()
c.connect()
print("connected")
while True:
inp = input(">>> ")
if inp == ":q":
break
reply = c.SocketQuery(c.s, inp.encode("UTF-8"))
if reply:
print(reply.decode("UTF-8"))
c.SocketClose(c.s)
So as i have already mentioned, they do connect, but dont send/receive messages.
i have checked the value in conn.recv(), and it is the same, also everything gets encoded to UTF-8 before sent, and then decoded back. I cant seem to find any other problem except that im running them all on localhost.
If anyone knows the answer to this, please tell me.
cheers!

Socket server - readlines() function causes my program to stop/stuck

I'm trying a example to create a simple socket server, I need to receive multiline data from clients so this is my code for the socket server:
import socket
import sys
host = 'localhost'
port = 5006
c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
c.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
c.bind((host, port))
c.listen(1)
while True:
try:
print("1")
csock, caddr = c.accept()
print("2")
with csock.makefile('rw', 2**16) as cfile:
print("3")
print(cfile.readline()) // When I use readline, it goes ok, but only get the first line, I need every line from data sent by client
print("4")
cfile.close()
print("5")
print("5.5")
csock.sendall("OK".encode('UTF-8'))
print("6")
csock.close()
print("7")
except KeyboardInterrupt:
print("Keyboard exit")
if 'csock' in locals():
csock.close()
sys.exit()
except Exception as e:
print(e)
Now when I use readlines(), my program just stuck and "does nothing" after print("3")
I tried with read() too, but still stuck, keep waiting both client and server
This is the code I'm using for client:
import socket
def query(host, port):
msg = \
'MSH|^~\&|REC APP|REC FAC|SEND APP|SEND FAC|20110708163513||QBP^Q22^QBP_Q21|111069|D|2.5|||||ITA||EN\r' \
'QPD|IHE PDQ Query|111069|#PID.5.2^SMITH||||\r' \
'RCP|I|'
# establish the connection
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((host, port))
# send the message
sock.sendall(msg.encode('UTF-8'))
# receive the answer
received = sock.recv(1024*1024)
return received
finally:
sock.close()
if __name__ == '__main__':
res = query('localhost', 5006)
print("Received response: ")
print(repr(res))
When I use readlines() and stop client after executing, server prints full message sent, I'm confused

Why this Python3 chat fails after a few messages?

That's what happens: After the client sends some messages, it gives ConnectionAbortedError: [WinError 10053] and the server keeps running
Images:
server socket:
client socket:
Here's my server code:
from socket import *
def server(address, port):
sock = socket(AF_INET, SOCK_STREAM)
sock.bind((address, port))
sock.listen(10)
while True:
clientsock, addr = sock.accept()
ip, _ = addr
msg = input('YOU: ')
clientsock.send(bytes(msg, 'utf-8'))
data = clientsock.recv(2048)
print('%s - ' % ip, data.decode('utf-8'))
if not data:
break
clientsock.shutdown(SHUT_WR)
clientsock.close()
sock.close()
if __name__ == '__main__':
server('192.168.0.101', 5000)
Client:
from socket import *
def client(address, port):
sock = socket(AF_INET, SOCK_STREAM)
sock.connect((address, port)) #0.0.0.0 isnt valid
while True:
data = sock.recv(2048)
print('%s - ' % address, data.decode('utf-8'))
msg = input('YOU: ')
sock.send(bytes(msg, 'utf-8'))
sock.close()
if __name__ == '__main__':
client('192.168.0.101', 5000)
Server in each loop accept new client sends one message receive one message and disconnect client. Then it waits for another client.
You need another loop for handling client.
That another loop could be placed in another thread.
If you nest that loop in this loop, you will be able to handle just one client at the time. I modified your server like that:
def server(address, port):
sock = socket(AF_INET, SOCK_STREAM)
sock.bind((address, port))
sock.listen(10)
while True: # server loop
clientsock, addr = sock.accept()
ip, _ = addr
msg = "Hello to client from %s" % ip
# next line is here because your client need message from server to send message
clientsock.send(bytes(msg, 'utf-8'))
while True: # client loop
data = clientsock.recv(2048)
msg = '%s - %s' % (ip, data.decode('utf-8'))
print(msg)
if not data:
break
clientsock.send(bytes(msg, 'utf-8')) # for multiple clients you need send msg to all
clientsock.shutdown(SHUT_WR)
clientsock.close()
sock.close()
To handle multiple clients you do not want to block server loop until client loop ends. You could run client loop in another thread and continue waiting for next client clientsock, addr = sock.accept().
Similarly you might want to separate receiving messages from server and waiting for client input.

Python UDP client-server with different matching incoming-outgoing ports

Based on the example at http://www.binarytides.com/programming-udp-sockets-in-python/ I modified it to run on python 3 and used two opposed ports on client and server, so replies from each one go to these ports. Here are my examples
Server:
'''
Simple udp socket server
'''
import socket
import sys
HOST = 'localhost'
PORT_IN = 8889 # Arbitrary non-privileged port
PORT_OUT = 8888
# Datagram (udp) socket
try :
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
print('Socket created')
except socket.error as e:
print(e)
sys.exit()
# Bind socket to local host and port
try:
s.bind((HOST, PORT_IN))
except socket.error as e:
print(e)
sys.exit()
print('Socket bind complete')
#now keep talking with the client
while 1:
# receive data from client (data, addr)
d = s.recvfrom(1024)
data = d[0]
addr = d[1]
if not data:
break
reply = 'OK...' + str(data)
s.sendto(reply.encode('UTF-8'), ('localhost', PORT_OUT))
print('Message[' + addr[0] + ':' + str(addr[1]) + '] - ' + str(data).strip())
s.close()
Client:
'''
udp socket client
Silver Moon
'''
import socket #for sockets
import sys #for exit
# create dgram udp socket
try:
s1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
except socket.error:
print('Failed to create socket')
sys.exit()
host = 'localhost'
port_out = 8889
port_in = 8888
counter = 0
while(1) :
# msg = b'aoua'
msg = 'aoua' + str(counter)
try :
#Set the whole string
s1.sendto(msg.encode('UTF-8'), (host, port_out))
# receive data from client (data, addr)
s2.bind(('localhost', port_in))
d = s2.recvfrom(1472)
reply = d[0]
addr = d[1]
print('Server reply : ' + str(reply))
except socket.error as e:
print(e)
# sys.exit()
counter += 1
Problem is with the client which cannot receive any response from server and d = s2.recvfrom(1472) hangs with error [WinError 10022] An invalid argument was supplied.
I've noticed a slightly different behaviour with sock.settimeout(seconds), but I really can't figure why. Isn't d = s2.recvfrom(buffer) supposed to wait for incoming data?
What am I missing here?
Damn... Just saw it. Silly mistake. Calling s2.bind(('localhost', port_in)) in Client inside the loop.

Resources