Python socket : Error receive data - python

I write a network application. The server has ability to find client base on given subnet. If the client receive authentication message from server, it will respond to server. Everything working good but server, it can't receiver from client.
Client :
def ListenServer():
# Listen init signal from Server to send data
HOST = '' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
# UDP Socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((HOST, PORT))
data, addr = s.recvfrom(1024)
if data == 'Authen':
SocketConnect(addr[0])
def SocketConnect(HOST):
# Connect to Server to send data
print HOST
PORT = 50008 # The same port as used by the server
# Create Socket
print "Create Socket"
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, e:
print "Error creating socket: %s" %e
sys.exit(1)
# Connect
print "Connect"
try:
s.connect((HOST, PORT))
except socket.error, e:
print "Connection error: %s" %e
sys.exit(1)
# Send Data
print "Send Data"
try:
s.sendall('Hello, world')
except socket.error, e:
print "Error sending data: %s" % e
sys.exit(1)
# Close Socket
s.close()
print "Close Socket"
ListenServer()
Server :
from netaddr import IPAddress
import socket
import sys
import ipaddress
import time
def FindAgent():
PORT = 50007 # Port use to find Agent
#Find broadcast address
"""IPAddress("255.255.255.0").netmask_bits() #Convert Subnet Mask to Prefix Length, Result is 24"""
try :
HOST = str(ipaddress.ip_network(u'192.168.10.0/24')[-1])
except ValueError as e :
"""e = sys.exc_info()[0] # Find Exception you need"""
print e
# UDP client
MESSAGE = "Authen"
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for x in range(0,2):
sock.sendto(MESSAGE, (HOST, PORT))
def ListenClient():
# Listen Client sent data
HOST = socket.gethostbyname(socket.gethostname())
PORT = 50008
# TCP socket
# Create Socket
print "Create Socket"
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, e:
print "Error creating socket: %s" %e
sys.exit(1)
# Bind
print "Bind"
try:
s.bind((HOST, PORT))
except socket.error, e:
print "Error bind: %s" %e
sys.exit(1)
# Listen
print "Listen"
try:
s.listen(10)
except socket.error, e:
print "Error listen: %s" %e
sys.exit(1)
# Accept data from client
print "Accept data from client"
try:
conn, addr = s.accept()
data = s.recv(1024)
except socket.error, e:
print "Error listen: %s" %e
sys.exit(1)
print data
s.close()
FindAgent()
ListenClient()
Error on Server :
Create Socket
Bind
Listen
Accept data from client
Error listen: [Errno 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied
[Finished in 0.8s with exit code 1]
[shell_cmd: python -u "C:\Users\Win7_Lab\Desktop\Server.py"]
[dir: C:\Users\Win7_Lab\Desktop]
[path: C:\Python27\;C:\Python27\Scripts;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\]
Without the line data = s.recv(1024) on Server, it working fine. But with it, the error show up. Can anybody please tell me why it happen ?

The crash come from s.recv(1024) as you said it's because the recieve (.recv()) methode on your server need to be called on the client connection.
Follow this example : here
Server file :
conn, addr = s.accept()
data = conn.recv(1024)
Client file :
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((HOST, PORT))
data = s.recv(1024)
As you see the client recieve data from socket (server).
And server recieve data from client connection.
Hope that was usefull.
Edit add some examples links.
You can find what you want in these tutorial:
How to use socket
How to create server with socket and select
Example client server giving time
Example chat client server

Related

Send and receive messages on same port? Peer to peer message app python

I'm trying to create a peer to peer message app, I understand I need each instance of the app to be both a server and a client as I've got for the below code but I'm wondering how to set up the ports, can I send and receive messages on the same port?
The below code is one instance of the app, I can communicate with another version but I have to set the other version to send messages on port 9000 and receive messages on 6190. This won't work going forward as how would a third user connect?
Current situation:
User 1: Receives on 9000, sends on 6190
User 2: Receives on 6190, sends on 9000
import socket
import time
import threading
global incoming
def server_socket(): #call server_socket() in build method?
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 9000))
s.listen(1)
host_name = socket.gethostname()
ip_address = socket.gethostbyname(host_name)
print("IP address is: ", ip_address)
except socket.error as e:
print("Socket Error !!", "Unable To Setup Local Socket. Port In Use")
while True:
conn, addr = s.accept()
incoming_ip = str(addr[0])
data = conn.recv(4096)
data = data.decode('utf-8')
print("message recieved is: ", data)
conn.close()
s.close()
def client_send_message():
message = "Hello World"
message = message.encode('utf-8')
c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
c.connect(("127.0.0.1", 6190))
except Exception as e:
print("Connection Refused", "The Address You Are Trying To Reach Is Currently Unavailable")
try:
c.send(message)
except Exception as e:
print(e)
c.close()
t = threading.Thread(target=server_socket)
t.start()
for i in range(5):
time.sleep(30)
client_send_message()
You currently use TCP and with this design you need a separat socket for each client. You can exchange data on this socket in both directions though. More common for peer to peer networks is UDP: here you can use a single socket to recvfrom data from arbitrary clients and sendto data to arbitrary clients.

Getting error non-blocking (10035) error when trying to connect to server

I am trying to simply send a list from one computer to another.
I have my server set up on one computer, where the IP address is 192.168.0.101
The code for the server:
import socket
import pickle
import time
import errno
HEADERSIZE = 20
HOST = socket.gethostbyname(socket.gethostname())
PORT = 65432
print(HOST)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(10)
while True:
conn, adrs = s.accept()
print(f"Connection with {adrs} has been established")
conn.setblocking(1)
try:
data = conn.recv(HEADERSIZE)
if not data:
print("connection closed")
conn.close()
break
else:
print("Received %d bytes: '%s'" % (len(data), pickle.loads(data)))
except socket.error as e:
if e.args[0] == errno.EWOULDBLOCK:
print('EWOULDBLOCK')
time.sleep(1) # short delay, no tight loops
else:
print(e)
break
The client is on another computer. The code:
import socket
import pickle
HOST = '192.168.0.101'
PORT = 65432
def send_data(list):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(10)
print(".")
print(s.connect_ex((HOST, PORT)))
print(".")
data = pickle.dumps(list)
print(len(data))
s.send(data)
s.close()
send_data([1,1,1])
The outputted error number of connect_ex is 10035. I read a lot about the error, but all I found was about the server side. To me, it looks like the problem is with the client and that it is unable to make a connection to 192.168.0.101. But then, I don't understand why the error I get is about non-blocking.
What is it that I am doing wrong that I am unable to send data?
First of all, how user207421 suggested, change the timeout to a longer duration.
Also, as stated here Socket Programming in Python raising error socket.error:< [Errno 10060] A connection attempt failed I was trying to run my server and connect to a private IP address.
The fix is: on the server side, in the s.bind, to leave the host part empty
HOST = ''
PORT = 65432
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
And on the client side, use the public IP of the PC where the server is running (I got it from ip4.me)
HOST = 'THE PUBLIC IP' #not going to write it
PORT = 65432
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, PORT))

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()

Errno 98: Address already in use - Python Socket

This question has been asked before but none of the answers was helpful in my case. The problem seems very simple. I am running a TCP server on an raspberry pi and try to connect to it from another machine. I have a custom class receiver that pipes sensor data to this script.
When I close the program running on the other machine (the socket is 'shutdown(2)'d and then 'close()'d), I cannot reconnect to that same port anymore. I tried to alternate between two sockets (1180 and 1181) but this did not work. When I connect over a port once, it is gone forever until I restart the TCP server. I tried restarting the script (with executl()) but that did not resolve my problem. I am telling the socket that it should re-use addresses but to no avail.
What I could do is use more ports but that would require opening more ports on the RPi which I would like to avoid (there must be another way to solve this).
import socket
from receiver import receiver
import pickle
import time
import os
import sys
TCP_IP = ''
TCP_PORT = 1180
BUFFER_SIZE = 1024
print 'Script started'
while(1):
try:
print 'While begin'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
print 'Socket created'
s.settimeout(5)
print 'Trying to bind'
s.bind((TCP_IP, TCP_PORT))
print 'bound to', (TCP_IP, TCP_PORT)
s.listen(1)
print 'listening for connection'
conn, addr = s.accept()
print 'accepted incoming connection'
s.settimeout(5)
r = receiver()
print 'Connection address:', addr
for cur in r:
#print "sending data:", cur
print len(cur.tostring())
conn.send(cur.tostring()) # echo
except Exception as e:
r.running = False
print e
if TCP_PORT == 1181:
TCP_PORT = 1180
else:
TCP_PORT = 1181
time.sleep(1)
print 'sleeping 1sec'
Your server socket is still in use, so you cannot open more than one server socket for each port. But why should one. Just reuse the same socket for all connections (that's what server sockets made for):
import socket
from receiver import receiver
import logging
TCP_IP = ''
TCP_PORT = 1180
BUFFER_SIZE = 1024
print 'Script started'
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
print 'Trying to bind'
server.bind((TCP_IP, TCP_PORT))
print 'bound to', (TCP_IP, TCP_PORT)
server.listen(1)
print 'listening for connection'
while True:
try:
conn, addr = server.accept()
print 'accepted incoming connection'
print 'Connection address:', addr
for cur in receiver():
data = cur.tostring()
#print "sending data:", cur
print len(data)
conn.sendall(data) # echo
except Exception:
logging.exception("processing request")

Socket based chat program doesn't work correctly

I'm trying to create a chatroom based on sockets which works on windows.
I have a server script:
# chat_server.py
import sys
import socket
import select
HOST = ''
SOCKET_LIST = []
RECV_BUFFER = 4096
PORT = 9009
def chat_server():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen(10)
threads = []
#add server socket object to the list of readable connections
SOCKET_LIST.append(server_socket)
print("Chat server started on port " + str(PORT))
while 1:
# get the list sockets wich are ready to be read through select
# 4th arg, tiome_out = 0 : poll and never block
ready_to_read,ready_to_write,in_error = select.select(SOCKET_LIST,[],[],0)
for sock in ready_to_read:
# a new connection request recieved
if sock == server_socket:
sockfd, addr = server_socket.accept()
SOCKET_LIST.append(sockfd)
print("Cient (%s, %s) connected" % addr)
broadcast(server_socket, sockfd, "[%s:%s] entered our chatting room\n" % addr)
# a message from a client, not a new connection
else:
# process data recieved from client,
try:
#receiving data from the socket.
data, addr = sock.recvfrom(RECV_BUFFER)
if data:
# there is something in the socket
broadcast(server_socket, sock, "\r" + '[' + str(sock.getpeername()) + ']' + data)
else:
# remove the socket that's broken
if sock in SOCKET_LIST:
SOCKET_LIST.remove(sock)
# at this stage, no data means probably the connection has been broken
broadcast(server_socket, sock, "Client (%s, %s) is offline\n" % addr)
# exception
except:
broadcast(server_socket, sock, "Client (%s, %s) is offline\n" % addr)
continue
server_socket.close()
# broadcast chat messages to all connected clients
def broadcast (server_socket, sock, message):
for socket in SOCKET_LIST:
# send the message only to peer
if socket != server_socket and socket != sock :
try :
socket.send(message)
except :
# broken socket connection
socket.close()
# broken socket, remove it
if socket in SOCKET_LIST:
SOCKET_LIST.remove(socket)
if __name__ == "___main__":
sys.exit(chat_server())
chat_server()
And a client script:
# chat_client.py
import sys
import socket
import select
from threading import Thread
def chat_client():
if(len(sys.argv) < 3):
print('Usage: python chat_client.py hostname port')
sys.exit()
host = sys.argv[1]
port = int(sys.argv[2])
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
#connect to remote host
try:
s.connect((host,port))
except:
print('Unable to connect')
sys.exit()
print('Connected to remote host. You can start sending messages')
sys.stdout.write('[Me] '); sys.stdout.flush()
sock_send = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock_send.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock_send.bind((host, port))
def send_msg(sock):
while True:
# user entered a message
s.send(sys.stdin.buffer.readline())
sys.stdout.write('[Me] '); sys.stdout.flush()
def recv_msg(sock):
while True:
# incoming message from remote server, s
data, addr = sock.recvfrom(1024)
if not data :
print('\nDisconnected from chat server')
sys.exit()
else:
#print data
sys.stdout.write(data)
sys.stdout.write('[Me] '); sys.stdout.flush()
Thread(target=send_msg, args=(sock_send,)).start()
Thread(target=recv_msg, args=(sock_send,)).start()
if __name__ == "__main__":
sys.exit(chat_client())
The program is executed with:
$ python chat_server.py
$ python chat_client.py localhost 9009
If I run the code I won't get any Error. When I run several clients at the same time they all connect to the server correctly, but one client doesn't get the text another client has written.
I think something is wrong with the server's broadcast function, but I'm not sure what it is.
I already searched for similar questions, but I didn't find anything useful for fixing this problem. Please Help!

Categories