Why Python Tcp client send close sign automatically? - python

I guess Python automatically send a close sign when shuts down(ctr+c) the client.
python tcp server
import socket
HOST = '127.0.0.1' # Standard loopback interface address (localhost)
PORT = 12345 # Port to listen on (non-privileged ports are > 1023)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
#if not data:break
conn.sendall(data)
print(data)
python tcp client
import socket
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 12345 # The port used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall(b'Hello, world')
data = s.recv(1024)
print('Received', data)
#s.close()
When executing this code,
the server continues to receive null data (maybe close sign) by the client that ended without closing.
Connected by ('127.0.0.1', 55305)
b'Hello, world'
b''
b''
b''
b''
b''
...
This error occurs when run node.js client and shutdown(ctr+c) without close sign.
The python tcp server occurs error but not print null.
node.js tcp client
const Net = require('net');
const client = new Net.Socket();
client.setEncoding('utf8');
client.connect({ port: 12345, host: '127.0.0.1' })
client.write('Hello, world');
/*client.end()*/
Connected by ('127.0.0.1', 56685)
b'Hello, world'
Traceback (most recent call last):
File "C:/.../server.py", line 13, in <module>
data = conn.recv(1024)
ConnectionResetError: [WinError 10054]An existing connection was forcibly closed by the remote host
I know that the server and the client need to send and receive the exit sign,
but I wonder why the Python client automatically sends the close sign when it is closed.
Where can I get information about this?

Related

How to send continous data from server to client in Python?

I am building a server to send data to the client in Python. I would like to continuously send the time until the client closes the connection. So far, I have done :
For the server:
import socket
from datetime import datetime
# take the server name and port name
host = 'local host'
port = 5001
# create a socket at server side
# using TCP / IP protocol
s = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
# bind the socket with server
# and port number
s.bind(('', port))
# allow maximum 1 connection to
# the socket
s.listen(1)
# wait till a client accept
# connection
c, addr = s.accept()
# display client address
print("CONNECTION FROM:", str(addr))
dateTimeObj = str(datetime.now())
print(dateTimeObj)
c.send(dateTimeObj.encode())
# disconnect the server
c.close()
For the client:
import socket
# take the server name and port name
host = 'local host'
port = 5001
# create a socket at client side
# using TCP / IP protocol
s = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
# connect it to server and port
# number on local computer.
s.connect(('127.0.0.1', port))
# receive message string from
# server, at a time 1024 B
msg = s.recv(1024)
# repeat as long as message
# string are not empty
while msg:
print('Received date :' + msg.decode())
msg = s.recv(1024)
# disconnect the client
s.close()
How can I modify the server to continously send the current date? At the moment, the server is just sending one date and closing the connection.
you need to use While True loop.
import socket
from datetime import datetime
# take the server name and port name
host = 'local host'
port = 5001
# create a socket at server side
# using TCP / IP protocol
s = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
# bind the socket with server
# and port number
s.bind(('', port))
# allow maximum 1 connection to
# the socket
s.listen(1)
# wait till a client accept
# connection
while True:
c, addr = s.accept()
# display client address
print("CONNECTION FROM:", str(addr))
dateTimeObj = str(datetime.now())
print(dateTimeObj)
c.send(dateTimeObj.encode())
# disconnect the server
c.close()
client:
import socket
# take the server name and port name
host = 'local host'
port = 5001
# create a socket at client side
# using TCP / IP protocol
s = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
# connect it to server and port
# number on local computer.
s.connect(('127.0.0.1', port))
# receive message string from
# server, at a time 1024 B
while True:
msg = s.recv(1024)
# repeat as long as message
# string are not empty
while msg:
print('Received date :' + msg.decode())
msg = s.recv(1024)
# disconnect the client
s.close()

Test TCP connection for Client & Server on local machine

I'm trying a simple send/receiver example on my local machine using TCP. The goal is to open a TCP server and send some data. My setup is Python3.6 on Pycharm IDE. I have enabled parallel run of the sender and receiver scripts.
Here is the Server script:
import socket
import sys
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('localhost', 5005)
print(sys.stderr, 'starting up on %s port %s' % server_address)
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)
while True:
# Wait for a connection
print(sys.stderr, 'waiting for a connection')
connection, client_address = sock.accept()
try:
print(sys.stderr, 'connection from', client_address)
# Receive the data in small chunks and retransmit it
while True:
data = connection.recv(16)
print(sys.stderr, 'received "%s"' % data)
if data:
print(sys.stderr, 'sending data back to the client')
connection.sendall(data)
else:
print(sys.stderr, 'no more data from', client_address)
break
finally:
# Clean up the connection
connection.close()
And here is the client script:
import socket
TCP_IP = 'localhost'
TCP_PORT = 5005
BUFFER_SIZE = 1024
MESSAGE = "Hello, World!"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(MESSAGE.encode('utf-8'))
I verified that both scripts are running and I've used the debugger to parse each line on the sender side. I get no errors but I also don't see that the server receives anything.
EDIT:
I have used an example code from this page
Server:
#!/usr/bin/env python3
import socket
HOST = '127.0.0.1' # Standard loopback interface address (localhost) PORT = 65432 # Port to listen on (non-privileged ports are > 1023)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data + b' from server')
Client:
#!/usr/bin/env python3
import socket
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 65432 # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b'Hello, world')
data = s.recv(1024)
print('Received', repr(data))
And I get the expected result:
Received b'Hello, world from server'
Hmm, the client scripts ends immediately after sending its data... This is at least dangerous! Race conditions could cause the connection to be destroyed before anything has been correctly received by the peer. The robust way would be to use a graceful shutdown client side:
...
s.send(MESSAGE.encode('utf-8'))
s.shutdown(socket.SHUT_WR) # tell peer we have nothing more to send
while True:
data = s.recv(256)
if len(data) == 0: # but keep on until peer closes or shutdowns its side
break
After that, I could test that your server script could correctly receive and send back the message:
<idlelib.run.StdOutputFile object at 0x0000021279F1CBB0> starting up on localhost port 5005
<idlelib.run.StdOutputFile object at 0x0000021279F1CBB0> waiting for a connection
<idlelib.run.StdOutputFile object at 0x0000021279F1CBB0> connection from ('127.0.0.1', 62511)
<idlelib.run.StdOutputFile object at 0x0000021279F1CBB0> received "b'Hello, World!'"
<idlelib.run.StdOutputFile object at 0x0000021279F1CBB0> sending data back to the client
<idlelib.run.StdOutputFile object at 0x0000021279F1CBB0> received "b''"
<idlelib.run.StdOutputFile object at 0x0000021279F1CBB0> no more data from ('127.0.0.1', 62511)
<idlelib.run.StdOutputFile object at 0x0000021279F1CBB0> waiting for a connection

ConnectionRefusedError when trying to host python socket server on raspberry pi

I'm trying to make a basic python networking program. All I'm trying to do is send strings of text back and forth between the server and the client. I'm trying to host the server on my Raspberry Pi, and connect with a client on Windows 10. The program works great locally on my computer, but when I try to connect to my server, it gives me ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it. My server code is as follows:
import socket # Import socket module
import netifaces as ni
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port))
#host_ip = ni.ifaddresses('wlan0')[ni.AF_INET][0]['addr']
host_ip = "bruh?"
print("Server started! \nHostname: " + host + " \nIP: " + host_ip + " \nPort: " + str(port))
s.listen() # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print('Got connection from', addr)
output = "Welcome to the server!".encode()
c.send(output)
c.close()
Client code:
import socket
s = socket.socket()
host = 192.168.1.21
port = 12345
s.connect((host, int(port)))
noResponse = False
serverResponse = s.recv(1024).decode()
print(serverResponse)
s.close()
Does anyone know what my problem is? Thanks.
There may be a few reasons you are getting a ConnectionRefusedError, please try the following:
Check that no firewall is blocking your connection.
Double-check the server IP, if it is wrong you may get this error.
Try to use Hercules to check the connection.
Also, I would change the code as follow:
Server:
import socket
HOST = '' # localhost
PORT = # IMPORTANT !! Do not use reserved ports
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind((HOST, PORT))
sock.listen()
conn, addr = sock.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
print('Data: ',data)
conn.sendall('RT')
Client:
import socket
HOST = '' # server IP address
PORT = # server port
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.connect((HOST, PORT))
sock.sendall('Hello, I am the Client')
data = sock.recv(1024)
print('Received', data)
By doing this you are using a TCP connection and you can test your code with different TCP server and client emulators.

Python s.recv() returns empty string

I've got a simple client and server I found on an online tutorial
#server.py
import socket # Import socket module
s = socket.socket() # Create a socket object
host = 'localhost' # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
c.send('Thank you for connecting')
c.close() # Close the connection
#client # This is client.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = 'localhost'
port = 12345 # Reserve a port for your service.
s.connect((host, port))
print s.recv(1024)
s.close # Close the socket when done
When I run my client.py all it does is print an empty string when it should print ('Thank you for connecting'). When I connect localhost 12345 from telnet it sends the message fine so I don't know why my client isn't receiving the message
Any thoughts. I'm very new to socket programming and would love to find a solution so I can move on.
While running your script as is, I got this error:
Waiting connections ...
Got connection from ('127.0.0.1', 63875)
Traceback (most recent call last):
File "serv.py", line 14, in <module>
c.send('Thank you for connecting')
TypeError: a bytes-like object is required, not 'str'
Few things here:
Ensure you're sending bytes instead of str. you could do this by replacing line 14 with:
c.send(b'Thank you for connecting')
Also, it's always useful to declare your sockets s like this:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Further read:
Py2: https://docs.python.org/2/library/socket.html
Py3: https://docs.python.org/3/library/socket.html
Hope it works! :)

How to use client socket as a server socket python

I like to have one port that first use for connect to another server and after that this port use to be a server and another clients connect to it.
I used python socket for client now I want to use it for server socket.
my code :
#!/usr/bin/python # This is server.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12349
portt = 12341 # Reserve a port for your service.
s.bind((host, portt)) # Bind to the port
s.connect((host, port))
s.listen(5) # Now wait for client connection.
c, addr = s.accept() # Establish connection with client.
print c
print 'Got connection from', addr
print s.recv(1024)
s.close
and the output is
Traceback (most recent call last):
File "client.py", line 12, in <module>
s.listen(5) # Now wait for client connection.
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 22] Invalid argument
How can I do that.
thank you for your answers!
Not sure what you are trying to do here. Seems to me that you are mixing client and server code in the same app.
For reference, you can create a simple echo server like this:
import socket
HOST = ''
PORT = 12349
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(5)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.sendall(data)
conn.close()
And a simple echo client like this:
import socket
HOST = 'localhost'
PORT = 12349
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)

Categories

Resources