Python Server & Client won't communicate - python

I've been following examples on a server and client communication within Python but I cannot get the server to constantly listen for new messages, print them and send them back for the client to print it as well. Any ideas what I'm doing wrong?
Server code:
#Imports
import socket
#Define socket address
TCP_IP = '0.0.0.0' # consider all incoming IPs
TCP_PORT = 5000 # port# communicating with the client
BUFFER_SIZE = 1024 # buffer size for receiving data
#Create socket IPv4 TCP
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Socket created"
s.bind((TCP_IP, TCP_PORT))
s.listen(20)
print "Waiting for a Cli_socket..."
#Wait for Cli_sockect
while True:
while True:
# accept Cli_sockection
Cli_sock, addr = s.accept()
print "Cli_sockected with " + addr[0] + " " + str(addr[1])
# get message from client
message = Cli_sock.recv(BUFFER_SIZE)
print message
# check that there is a message
if not message:
break
# send message to client
Cli_sock.send(message)
print "Sent message"
s.close()
print "Socket Closed"
Client code:
# a simple client socket
import socket
# define socket address
TCP_IP = '127.0.0.1' # ip of connecting server
TCP_PORT = 5000 # port communicating server
BUFFER_SIZE = 1024 # buffer size receiving data
# create socket IPv4 & TCP protocol
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Socket created successfully."
# connect to server
s.connect((TCP_IP, TCP_PORT))
print "Established connection with the server."
data = s.recv(BUFFER_SIZE)
while True:
print ("Message to send:")
message = raw_input()
s.send(message)
print "Message sent to server: %s." % message
print ("Message Recv:%s\n" % data)

Your server is waiting for data from the client before sending anything:
Cli_sock, addr = s.accept()
print "Cli_sockected with " + addr[0] + " " + str(addr[1])
# get message from client
message = Cli_sock.recv(BUFFER_SIZE)
Your client is waiting for data from the server before sending anything:
s.connect((TCP_IP, TCP_PORT))
print "Established connection with the server."
data = s.recv(BUFFER_SIZE)
Thus both wait for each other to send data but nobody does. That's why it hangs.

Related

Unable to send file from client/server -socket pgm-Python 3

From client I am trying to send a txt file to server.
client.py
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 8340
BUFFER_SIZE = 1024
server_addr = (TCP_IP, TCP_PORT)
c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
c.connect(server_addr)
file = open(r"C:\Users\sakthi\Desktop\Hi.txt",'r')
transfer = file.read(BUFFER_SIZE)
while transfer:
c.send(transfer.encode())
transfer = file.read(1024)
print (s.recv(BUFFER_SIZE).decode())
c.close()
Server.py
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 8340
BUFFER_SIZE = 1024 # Normally 1024, but we want fast response
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
final = open(r"C:\Users\sakthi\Desktop\final.txt", 'a+')
while 1:
print('Connection address:', addr)
r = conn.recv(BUFFER_SIZE).decode()
if not r:break
final.write(r)
print("received data:", r)
k="file received"
conn.send(k.encode())
conn.close()
Once the file is received, server will send message "file received" to client.
Client will print the message "file received" and close the connection
When I run the code, server.py is not coming out of while loop
while 1:
print('Connection address:', addr)
r = conn.recv(BUFFER_SIZE).decode()
if not r:break
final.write(r)
print("received data:", r)
r = conn.recv(BUFFER_SIZE).decode() keeps listening for new messages, but the client has transferred all messages.
size of the file is 1.14 KB.
Can anybody tell me what's wrong in my program?
I found the solution
Note our statement that recv() blocks until either there is data available to be read or the sender has closed the connection holds only if the socket is in blocking mode. That mode is the default, but we can change a socket to nonblocking mode by calling setblocking() with argument 0.
I have modified the server.py
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 8340
BUFFER_SIZE = 1024 # Normally 1024, but we want fast response
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
conn.setblocking(0)
final = open(r"C:\Users\sakthi\Desktop\final.txt", 'a+')
while 1:
try:
print('Connection address:', addr)
r = conn.recv(BUFFER_SIZE).decode()
final.write(r)
print("received data:", r)
except:
break
k="file received"
conn.send(k.encode())
conn.close()
Now I am able to receive the file and send message "file received" to client and connection is closed.
non-blocking socket,error is always
http://www.mws.cz/files/PyNet.pdf

Trying to create messenger application python

Trying to Create Messenger Application within python (cross internet). So far I have successfully been able to send a message to the receiver end and then ping the message back to the user that sent it. However, it does not send the message to all connected users. I think this is because if python is listening for user input the socket cannot receive any data (I might be wrong...).
Below is the client side code:
import socket
host = '**.***.***.***' # Public Ip Hidden
port = 5005 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
b = input("Please enter your message.")
b = b.encode('utf-8')
s.sendall(b)
while True:
data = s.recv(1024)
print('Message Received:', repr(data))
Now below is the server side code:
import socket
import sys
import os
import thread
import threading
from thread import *
from threading import Thread
HOST = '' # Symbolic name meaning all available interfaces
PORT = 5005 # Arbitrary non-privileged port
BUFFER_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client = ''
clients = set()
clients_lock = threading.Lock()
print 'Socket created'
#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error as msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
#Start listening on socket
s.listen(10)
print 'Socket now listening'
#Function for handling connections. This will be used to create threads
def clientthread(conn):
#infinite loop so that function do not terminate and thread do not end.
with clients_lock:
clients.add(client)
while True:
#Receiving from client
data = conn.recv(1024)
if not data:
break
else:
print repr(data)
with clients_lock:
for c in clients:
for d in data:
conn.sendall(data)
print(data.decode("utf-8"))
#came out of loop
conn.close()
#now keep talking with the client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
start_new_thread(clientthread ,(conn,))
s.close()
Any Suggestions would be much appreciated.

How to avoid the following discrepancy in my chatting app between client and server?

As in my chatting app here, when client sends a message sends a message to server it becomes necessary for server to send a reply before client can send a message again. How to avoid this?
Server program:
from socket import *
import threading
host=gethostname()
port=7776
s=socket()
s.bind((host, port))
s.listen(5)
print "Server is Ready!"
def client():
c, addr= s.accept()
while True:
print c.recv(1024)
c.sendto(raw_input(), addr)
for i in range(1,100):
threading.Thread(target=client).start()
s.close()
Client program:
from socket import *
host=gethostname()
port=7776
s=socket()
s.connect((host, port))
while True:
s.send(( raw_input()))
data= s.recv(1024)
if data:
print data
s.close()
I am pretty sure you were meant to make the central server receive messages from clients, and send them to all other clients, was it not? What you implemented isn't exactly that - instead, the server process just prints all messages that arrive from the clients.
Anyways, based on the way you implemented it, here's a way to do it:
Server:
from socket import *
import threading
def clientHandler():
c, addr = s.accept()
c.settimeout(1.0)
while True:
try:
msg = c.recv(1024)
if msg:
print "Message received from address %s: %s" % (addr, msg)
except timeout:
pass
host = "127.0.0.1"
port = 7776
s = socket()
s.bind((host, port))
s.listen(5)
for i in range(1, 100):
threading.Thread(target=clientHandler).start()
s.close()
print "Server is Ready!"
Client:
from socket import *
host = "127.0.0.1"
port = 7776
s = socket()
s.settimeout(0.2)
s.connect((host, port))
print "Client #%x is Ready!" % id(s)
while True:
msg = raw_input("Input message to server: ")
s.send(msg)
try:
print s.recv(1024)
except timeout:
pass
s.close()

TCP Python Socket Server Response

I'm writing a TCP python script that will act as a server and retrieve a temperature reading from a machine (the client). I need to pass a command to the client from the server and listen for an output of the response. I successfully reach the cmd definition line, but when s.accept() is called I'm left hanging with no response from the client.
Server.py
import socket
port = 7777
ip = raw_input('192.168.62.233')
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((ip, port))
s.listen(1)
print "waiting on port: ", port
while True:
cmd = raw_input('KRDG? A[term]')#command send to client
conn, addr = s.accept()
s.send(cmd)
print "It sent"
data = conn.recv(4096)
print "Received:", data, " from address ", addr
Edit:
I believe you're correct, I should consider my code the client and temperature readout at the server. I do now get left hanging after "here 2" when I go to s.recv().
Client.py
import socket
ip = '192.168.62.233'
port = 7777 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ip, port))
print 'here'
s.send('KRDG? A[term]')
print 'here 2'
data = s.recv(4096)
print 'here 3'
s.close()
print 'Received', repr(data)
Usually, a TCP server accept will block while it waits for a client to connect. Have you checked to make sure that you client can and is connecting? You could use a tool like tcpdump or similar to watch the network activity and make sure the client is connecting.

multiple clients cannot listen and write at the same time

I'm writing a very basic chat room in python. Clients connect and any message from a client is relayed to all clients. The problem I'm having is getting the client to listen and send messages at the same time. It seems to only do either one. I've set up a separate listening client and confirmed that the message is received but the listening server cannot send anything.
Currently the client has to send data before getting a response from the server, but I want clients to be able to receive data before sending - otherwise the chat room won't work. I attempted using clientsock.settimeout() and then use recv but it did not solve the issue as it did not move past the input part.
server.py
#!/usr/bin/python
#socket server using threads
import socket, sys, threading
from _thread import *
HOST = 'localhost'
PORT = 2222
lock = threading.Lock()
all_clients = []
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ("Socket created")
#bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error as msg:
print ("Bind failed. Error code: " + str(msg[0]) + ' Message ' + msg[1])
sys.exit(0)
print ("Socket bind complete")
#Start listening on socket
s.listen(5)
print ("Socket now listening")
#function for handling connections. This will be used to create threads
def clientthread(conn):
#sending message to connected client
conn.send("Welcome to the server. Type something and hit enter\n".encode('utf-8'))
#infinite loop so that function does not terminate and thread does not end
while True:
#receiving data from client
data = conn.recv(1024)
reply = "OK..." + str(data, "utf-8")
if not data:
break
with lock:
for c in all_clients:
c.sendall(reply.encode('utf-8'))
#came out of loop
conn.close()
#keep talking with the client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
with lock:
all_clients.append(conn)
print ("Connected with " + addr[0] + ":" + str(addr[1]))
#start new thread takes 1st argument as a function name to be run, second
#is the tuple of arguments to the function
start_new_thread(clientthread ,(conn,))
s.close()
client.py
#!/usr/bin/python
import socket, sys
#client to transfer data
def main():
#create tcp stocket
clientsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#connect the socket to the server open port
server_address = ('localhost', 2222)
print ("connecting to %s port %s" % server_address)
clientsock.connect(server_address)
#receive data
data = clientsock.recv(1024)
print(str(data, "utf-8"))
while 1:
#send data
message = "sean: " + input()
clientsock.send(message.encode('utf-8'))
#look for the response
amount_received = 0
amount_expected = len(message)
while amount_received < amount_expected:
data = clientsock.recv(1024)
amount_received += len(data)
print ("received %s " % data)
print ("closing socket")
clientsock.close()
main()
new_client.py
#!/usr/bin/python
import socket, sys
from threading import Thread
#client for chat room
def send_msg(sock):
while True:
data = input()
sock.send(data.encode('utf-8'))
def recv_msg(sock):
while True:
stuff = sock.recv(1024)
sock.send(stuff)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 2222)
sock.connect(server_address)
print("Connected to chat")
Thread(target=send_msg, args=(sock,)).start()
Thread(target=recv_msg, args=(sock,)).start()
Create two threads, one for receiving the other for sending. This is the simplest way to do.
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect("address")
def send_msg(sock):
while True:
data = sys.stdin.readline()
sock.send(data)
def recv_msg(sock):
while True:
data, addr = sock.recv(1024)
sys.stdout.write(data)
Thread(target=send_msg, args=(sock,)).start()
Thread(target=recv_msg, args=(sock,)).start()

Categories