Errno 98: Address already in use - Python Socket - python

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

Related

Connecting client and server in python the code below dont give output make browser busy

This code is not giving output it just makes the browser busy. Any idea why?
import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
s.connect(('127.0.0.1', port))
print (s.recv(1024))
s.close
import socket
s=socket.socket()
host = socket.gethostname()
port = 12345
s.bind(('127.0.0.1', port))
s.listen(5)
while True:
c,addr = s.accept()
print ('Got connection from', addr)
c.send('Thank you for connecting')
c.close()
client program:
import socket
f=open("hello.txt","r").read()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 12345
s.connect(('127.0.0.1', port))
s.sendall(str.encode(f))
print (s.recv(1024).decode('ascii'))
s.close()
server program:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ("Socket successfully created")
port = 12345
s.bind(('', port))
print ("socket binded to %s" %(port))
f=open("hi.txt","r").read()
s.listen(5)
print ("socket is listening")
while True:
c, addr = s.accept()
print ('Got connection from', addr)
print (c.recv(1024).decode('ascii'))
c.sendall(str.encode(f))
c.close()
server output:
Socket successfully created
socket binded to 12345
socket is listening
Got connection from ('127.0.0.1', 51630)
helloooooo
client output:
hiiiii
Open the two programs in seperate shells.
Run server program first then client program.
Dont close the server program before running client program.
Create two files one for server and one for client.
Read the data from those files and send it.
While receiving the data decode it and print it.
You can send entire data from files or just a single line it depends on you.
To know more about reading,writing and creating files you can refer https://docs.python.org/release/3.6.5/tutorial/inputoutput.html#reading-and-writing-files
Let me know if it worked :)

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

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

Python socket multiple calls using Eventlet

I need to call a socker server multiple times and print its output.
Here is my below code:-
server.py
import socket
s = socket.socket()
host = socket.gethostname()
port = 1234
s.bind((host, port))
s.listen(5)
print "Server started"
while True:
c, addr = s.accept()
print('Got connection from', addr)
#sprint('Received message == ',c.recv(50))
s = c.recv(50)[::-1]
c.send(s)
c.close()
client.py
import socket
from time import sleep
import eventlet
def socket_client():
s = socket.socket()
host = socket.gethostname()
port = 1234
s.connect((host, port))
print "Sending data"
s.sendall("Hello!! How are you")
print(s.recv(1024))
#socket_client()
pile = eventlet.GreenPile()
for x in range(10):
print 'new process started'
pile.spawn(socket_client())
print 'new process started over'
print 'over'
I use a python eventlet to call the socket_client() 10 times but its not returning the correct result..
You're overriding variable with socket by string received from socket:
s = socket.socket()
...
s = c.recv(50)[::-1]
Pick different variable name for the second case.

python socket send not working

Im writing a simple socket program to receive some data and reverse the contents.
When I pass the reversed contents its not being sent..
Server
import socket
s = socket.socket()
host = socket.gethostname()
port = 1234
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
print('Got connection from', addr)
print('Received message == ',c.recv(50))
s = c.recv(50)[::-1]
c.send(s)
c.close()
client
import socket
from time import sleep
s = socket.socket()
host = socket.gethostname()
port = 1234
s.connect((host, port))
print "Sending data"
s.sendall("Hello!! How are you")
print(s.recv(1024))
The problem is two lines in your server
Your server calls recv() inside a print statement. This empties the buffer. Then you call recv() again, but it is already emptied by the previous statement and so it then blocks.
You need to call recv() and store that in s. Then use s everywhere else.
Try this for your server:
import socket
s = socket.socket()
host = socket.gethostname()
port = 1234
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
print('Got connection from', addr)
s = c.recv(50)
print('Received message == ',s)
c.send(s)
c.close()

Categories