Test TCP connection for Client & Server on local machine - python

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

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

Why Python Tcp client send close sign automatically?

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?

Python - how to stop socket recv() waiting if there is no coming data sent from client

I'm leanring how sockets work and trying to do some simple things.
My client is NOT sending anything to the server, and the server will not receive anything. But the problem is that the server socket will be always waiting for nothing. I want it to do something else if there is no available coming data from the client side. The if statement does not help end its waiting.
Server.py:
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
hostname = socket.gethostname()
host = socket.gethostbyname(hostname)
port = 9090
server.bind((host, port))
server.listen(10)
con, addr = server.accept()
msg = con.recv(2048)
if not msg:
con.send('hello world'.encode('utf-8'))
con.close()
server.close()
else:
con.send('hi Client I received it'.encode('utf-8'))
con.close()
server.close()
Client.py:
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('192.155.11.79', 9090))
data = client.recv(2048).decode('utf-8')
print('From server side: ', data)
client.close()

How to send a message from client to server in python

I'm reading two programs in Python 2.7.10 with client and server. How can I modify these programs in order to send a message from client to server?
server.py:
#!/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 = 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.py:
#!/usr/bin/python # This is client.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 80 # Reserve a port for your service.
s.connect((host, port))
print s.recv(1024)
s.close # Close the socket when done
TCP sockets are bi-directional. So, after connection, there is no difference between server and client, you only have two ends of a stream:
import socket # Import socket module
s = socket.socket() # Create a socket object
s.bind(('0.0.0.0', 12345)) # 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
print c.recv(1024)
c.close() # Close the connection
and the client:
import socket # Import socket module
s = socket.socket() # Create a socket object
s.connect(('localhost', 12345))
s.sendall('Here I am!')
s.close() # Close the socket when done
The above answer throws an error: TypeError: a bytes-like object is required, not 'str'
However, the following code worked for me:
server.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 3125
s.bind(('0.0.0.0', port))
print ('Socket binded to port 3125')
s.listen(3)
print ('socket is listening')
while True:
c, addr = s.accept()
print ('Got connection from ', addr)
print (c.recv(1024))
c.close()
client.py:
import socket
s = socket.socket()
port = 3125
s.connect(('localhost', port))
z = 'Your string'
s.sendall(z.encode())
s.close()

Python Socket Error "Only one usage of each socket address is normally permitted"

I have a basic server and client that prints a message on the server when a client connects, and then prints a message on the client saying "Thanks for connecting." But when I try to run the server again(after closing it), I get "error: Only one usage of each socket address is normally permitted"(Not exact). And when I change the port again it works.
#Server
import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
print 'Got connection from', addr
c.send('Thank you for connecting')
c.close()
.
#Client
import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
s.connect((host, port))
print s.recv(1024)
s.close
If I change the last two lines of code for the server to
break
c.close()
it works but closes the server.
How can I keep the server up after the client disconnects without having to change the port each time?
You want to set the socket option SO_REUSEADDR:
Example:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

Categories

Resources