Python server chat issue when run - python

I've been programming my chat but then I get an error which crashes the server and so then the next time I won't be able to use the same port and so I get socket.bind error when I run it again. How to fix?
Source code:
import socket
from threading import Thread
def clientHandler():
conn, addr = sock.accept()
print addr, "is Connected"
while 1:
data = conn.recv(1024)
if not data:
break
print "Received Message", repr(data)
HOST = ''
PORT = raw_input('PORT: ')
PORT = int(PORT)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((HOST, PORT))
sock.listen(5)
print "Server is running......"
#Thread(target=clientHandler).start()
#Thread(target=clientHandler).start()
#Thread(target=clientHandler).start()
for i in range(5):
Thread(target=clientHandler).start()
sock.close()
This is what happens:
Server is running......
Exception in thread Thread-5:
Traceback (most recent call last):
File "C:\Python27\lib\threading.py", line 810, in __bootstrap_inner
self.run()
File "C:\Python27\lib\threading.py", line 763, in run
self.__target(*self.__args, **self.__kwargs)
File "C:/Users/Judicaƫl/Desktop/server_test.py", line 5, in clientHandler
conn, addr = sock.accept()
File "C:\Python27\lib\socket.py", line 202, in accept
sock, addr = self._sock.accept()
File "C:\Python27\lib\socket.py", line 170, in _dummy
raise error(EBADF, 'Bad file descriptor')
error: [Errno 9] Bad file descriptor
>>> ==================================================== RESTART ====================================================
>>>
Traceback (most recent call last):
File "C:/Users/Judicaƫl/Desktop/server_test.py", line 15, in <module>
sock.bind((HOST, PORT))
File "C:\Python27\lib\socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
error: [Errno 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted
I am using Win7 64bit python 2.7.6 64bit version
and is there also a way to restore the ports which had been blocked or does it auto restore when restart comp?
*******FIXED by Daniel************
Fixed Code:
import socket, sys
from threading import Thread
def clientHandler(conn, addr):
print addr, "is Connected"
while 1:
data = conn.recv(1024)
if data == 'Admin: /server shutdown':
sock.close()
print 'quitting...'
quit()
if not data:
break
conn.sendall(data) # only sends to original sender
print "Received Message", repr(data)
HOST = ''
PORT = int(raw_input('PORT: '))
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((HOST, PORT))
sock.listen(999999)
print "Server is running......"
#Thread(target=clientHandler).start()
#Thread(target=clientHandler).start()
#Thread(target=clientHandler).start()
for i in range(999999):
conn, addr = sock.accept()
Thread(target=clientHandler, args=(conn, addr)).start()
sock.close()
How do I now send the messages received to all clients?

The functions you have to call at server side is the following:
- create a socket
- bind it to a port
- listen
- accept
- handle the client communication
You have multiple threads for accept. Then you close the socket, so all accepts fail.
The correct way is
while True:
client, addr = sock.accept()
Thread(target=clientHandler, args=(client, addr)).start()

Related

multiprocessing.Pool ==> TypeError: expected string or Unicode object, NoneType found

These are some Python scripts to get mac from client nodes via socket.
I use multiprocessing.pool to make it run faster, but I get this error:
TypeError: expected string or Unicode object, NoneType found
Here the code I am using:
server:
import os
import re
import socket
import sys
import multiprocessing
def get_mac(cli, caddr):
while True:
macinfo = cli.recv(1024)
if macinfo:
print('get [{}] from {}'.format(macinfo, caddr))
else:
print('establish but get nothing from {}'.format(caddr))
print('TERMINAL CLI-SOCKET')
cli.close()
cli.sendall('Done')
log.info('Send Confirm <Done> To {}'.format(caddr))
info = macinfo.split(',').strip()
return info
def gen_config(info):
print(info)
def start(func):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
addr = ('mn0', 1995)
sock.bind(addr)
sock.listen(5)
pool = multiprocessing.Pool()
while True:
print('waitting for new connect ...')
cli, caddr = sock.accept()
print('establish new connect with {}'.format(caddr))
pool.apply_async(func, args=(cli, caddr,), callback=gen_config)
pool.close()
pool.join()
if __name__ == '__main__':
start(get_mac)
client:
#!/usr/bin/env python
import socket
def send():
addr = ('mn0', 1995)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(addr)
print('Establish Connect with {}'.format(addr))
sock.sendall('{},{}'.format('192.168.85.1', 'da:ad:as:as:as:sa'))
print('send 192.168.85.1 da:ad:as:as:as:sa')
data = sock.recv(1024)
if data == 'Done':
print('Confirm Send')
sock.close()
if __name__ == '__main__':
send()
full error mesg:
[root#mn0 svr]# python svr.py
waitting for new connect ...
establish new connect with ('192.168.85.128', 52798)
waitting for new connect ...
Exception in thread Thread-2:
Traceback (most recent call last):
File "/usr/lib64/python2.7/threading.py", line 812, in __bootstrap_inner
self.run()
File "/usr/lib64/python2.7/threading.py", line 765, in run
self.__target(*self.__args, **self.__kwargs)
File "/usr/lib64/python2.7/multiprocessing/pool.py", line 342, in _handle_tasks
put(task)
TypeError: expected string or Unicode object, NoneType found

Python - Client and server communication

I've written a python script that will communicate with a server, get its data and will send the data back to the server, some sort of an "echo client".
This is what I've written:
import socket
import time
def netcat(hostname, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((hostname, port))
s.shutdown(socket.SHUT_WR)
while 1:
data = s.recv(1024)
if data == "":
break
print "Received:", repr(data)
data = data.replace("\n", "")
time.sleep(1)
s.sendall(data)
print "Sent:", data
print "Connection closed."
s.close()
netcat("127.0.0.1", 4444)
I get this output:
Received: 'Welcome!\n'
And after that, I get this error:
Traceback (most recent call last):
File "client.py", line 22, in <module>
netcat("127.0.0.1", 4444)
File "client.py", line 17, in netcat
s.sendall(data)
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 32] Broken pipe
I've looked already for a solution for this error online, but with no luck.
Can someone please help me figure it out?
Thank you
I've been working on sockets a lot lately. I don't have a server right now to test your code so I thought I would quickly comment on what I see. You seem to be shutting down the socket (for writing) at the beginning, so your receive statement worked, but your sendall statement fails.
def netcat(hostname, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((hostname, port))
s.shutdown(socket.SHUT_WR) <-- WHY IS THIS HERE?

Python P2P sockets error "This operation would block forever"

Hello I'm trying to create a P2P program to distribute messages throgh the clients.
My server.py:
import requests
from flask import Flask, jsonify, request
import logging
from daemon import Daemon
import time
import argparse
import sys
from transaction import Transaction
import settings
import socket
import threading
bind_ip = '139.59.26.12'
bind_port = 9998
my_node_addr = str(bind_ip) + ":" + str(bind_port)
clients = [("0.0.0.0", 9999), ("0.0.0.0", 9998)]
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bind_ip, bind_port))
server.listen(5) # max backlog of connections
print('Listening on {}:{}'.format(bind_ip, bind_port))
numbers = []
def broadcast_info(info):
for n in clients:
node_str_addr = str(n[0]) + ":" + str(n[1])
print("Selected: " + node_str_addr)
if node_str_addr != my_node_addr:
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((n[0], n[1]))
client.send(info)
response = client.recv(4096)
def handle_client_connection(client_socket):
request = client_socket.recv(1024)
request_str = request.decode()
if request_str == 'print':
client_socket.send(str(numbers).encode('utf-8'))
print(numbers)
else:
client_socket.send('Added!'.encode('utf-8'))
client_socket.close()
num_rec = int(request.decode())
if num_rec not in numbers:
numbers.append(num_rec)
#broadcast_info(request)
while True:
client_sock, address = server.accept()
print('Accepted connection from {}:{}'.format(address[0], address[1]))
client_handler = threading.Thread(
target=handle_client_connection,
args=(client_sock,)
# without comma you'd get a... TypeError: handle_client_connection() argument after * must be a sequence, not _socketobject
)
client_handler.start()
And my client:
import socket
hostname, sld, tld, port = 'www', 'integralist', 'co.uk', 80
target = '{}.{}.{}'.format(hostname, sld, tld)
# create an ipv4 (AF_INET) socket object using the tcp protocol (SOCK_STREAM)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# connect the client
# client.connect((target, port))
client.connect(('139.59.76.32', 9998))
# send some data (in this case a HTTP GET request)
client.send("2".encode('utf-8')) # Number or "print"
# receive the response data (4096 is recommended buffer size)
response = client.recv(4096)
print (response)
client.close()
Sometimes it works well. But then after a few tries this error appears:
Exception in thread Thread-11:
Traceback (most recent call last):
File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
self.run()
File "/usr/lib/python3.5/threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
File "server.py", line 43, in handle_client_connection
request = client_socket.recv(1024)
File "/usr/local/lib/python3.5/dist-packages/gevent/_socket3.py", line 336, in recv
self._wait(self._read_event)
File "/usr/local/lib/python3.5/dist-packages/gevent/_socket3.py", line 156, in _wait
self.hub.wait(watcher)
File "/usr/local/lib/python3.5/dist-packages/gevent/hub.py", line 651, in wait
result = waiter.get()
File "/usr/local/lib/python3.5/dist-packages/gevent/hub.py", line 898, in get
return self.hub.switch()
File "/usr/local/lib/python3.5/dist-packages/gevent/hub.py", line 630, in switch
return RawGreenlet.switch(self)
gevent.hub.LoopExit: ('This operation would block forever', <Hub at 0x7fdf21aa2af8 epoll pending=0 ref=0 fileno=9>)
I tried everything. In my local machine works fine. But when I try to do it on my Digitalocean VPS, then this happens. I've search about this error over the Internet but I can't find anything that helps me.
Do you know what can be the cause of this error?
Thanks

Creating non-blocking socket in python

I was trying to understand how non-blocking sockets work ,so I wrote this simple server in python .
import socket
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1',1000))
s.listen(5)
s.setblocking(0)
while True:
try:
conn, addr = s.accept()
print ('connection from',addr)
data=conn.recv(100)
print ('recived: ',data,len(data))
except:
pass
Then I tried to connect to this server from multiple instances of this client
import socket
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1',1000))
while True:
continue
But for some reason putting blocking to 0 or 1 dose not seem to have an effect and server's recv method always block the execution.
So, dose creating non-blocking socket in python require more than just setting the blocking flag to 0.
setblocking only affects the socket you use it on. So you have to add conn.setblocking(0) to see an effect: The recv will then return immediately if there is no data available.
You just need to call setblocking(0) on the connected socket, i.e. conn.
import socket
s = socket.socket()
s.bind(('127.0.0.1', 12345))
s.listen(5)
s.setblocking(0)
>>> conn, addr = s.accept()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.7/socket.py", line 202, in accept
sock, addr = self._sock.accept()
socket.error: [Errno 11] Resource temporarily unavailable
# start your client...
>>> conn, addr = s.accept()
>>> conn.recv() # this will hang until the client sends some data....
'hi there\n'
>>> conn.setblocking(0) # set non-blocking on the connected socket "conn"
>>> conn.recv()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
socket.error: [Errno 11] Resource temporarily unavailable
https://docs.python.org/3/library/socket.html#socket.setdefaulttimeout
You can use s.setdefaulttimeout(1.0) to apply all connection sockets as default.

socket server on a thread not releasing the port after the process terminates

The following code runs a socket server on a thread. The client socket sends 'client: hello' to the server, and the server socket receives and replies 'server: world'.
import socket
import threading
def server():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('127.0.0.1', 12345))
sock.listen(1)
req, addr = sock.accept()
print req.recv(1024)
req.sendall('server: world')
def client():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('127.0.0.1', 12345))
sock.sendall('client: hello')
print sock.recv(1024)
def main():
t = threading.Thread(target=server)
t.start()
client()
if __name__ == '__main__':
main()
It runs ok as expected the first time, but from the second time, if you do not wait for a good few seconds for the server to release the socket, and if you try this on a Linux machine or Mac (Windows do not get it somehow) you will run into this error:
Traceback (most recent call last):
File "socket_send_receive.py", line 24, in <module>
main()
File "socket_send_receive.py", line 21, in main
client()
File "socket_send_receive.py", line 14, in client
sock.connect(('127.0.0.1', 12345))
File "<string>", line 1, in connect
socket.error: [Errno 111] Connection refused
Exception in thread Thread-1:
Traceback (most recent call last):
File "/home/cxuan/python/2.6/lib/python2.6/threading.py", line 532, in __bootstrap_inner
self.run()
File "/home/cxuan/python/2.6/lib/python2.6/threading.py", line 484, in run
self.__target(*self.__args, **self.__kwargs)
File "socket_send_receive.py", line 6, in server
sock.bind(('127.0.0.1', 12345))
File "<string>", line 1, in bind
error: [Errno 98] Address already in use
I am looking for some insight into why this is happening and if it is possible to be genuinely resolved or what best practice should be adopted.
I know already using this option can be a workaround thanks to the other posts here on stackoverflow.
socket.SO_REUSEADDR
When a socket is closed, it ends up in a state called STATE_WAIT (see this diagram). While the socket is in this state, no one else can use the same address (ip-number/port pair) unless the SO_REUSEADDR option is set on the socket.
See e.g. the Wikipedia article on TCP for more information about how TCP works and the different states.

Categories

Resources