I am new to opening a port and server side programming. And I am trying to open a port on my server in python and then form an iOS app get some data from that port. I have done some research and know I can open a port like this
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
But my question is lets say I just wanted to retrieve a simple string from this port how do I add that string to this open port, I have found some ways to get data from the port in iOS like this library https://github.com/armadsen/ORSSerialPort but how do I put the data like a string on the open port?
Thanks for the help in advance.
When you call the method s.accept() it will return the socket object as the first return. You can call socket.rescv method to read data -
data = c.recv(1024)
But do remember this is a blocking call. For more information, you can read this post.
Related
I have created a simple python server that sends back everything it receives.
I wonder if it would be possible to close the connection immediately after sending the data to the client (web browser), and the client then displays the data it has received. Currently, the client displays The connection was reset.
Thanks
#!/user/bin/env python3
import socket
HOST = 'localhost' # loopback interface address
PORT = 3000 # non-privileged ports are > 1023
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
while True:
# connect to the next client in queue
conn, addr = s.accept()
with conn:
print('Connected by', addr)
data = conn.recv(1024).decode()
print(data)
conn.sendall(data.encode())
Solution
#!/user/bin/env python3
import socket
HOST = 'localhost' # loopback interface address
PORT = 3000 # non-privileged ports are > 1023
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
while True:
# connect to the next client in queue
conn, addr = s.accept()
print('Connected by', addr)
data = conn.recv(1024).decode()
print(data)
conn.sendall(data.encode())
conn.shutdown(socket.SHUT_WR) # changed
Explanation
The solution uses conn.shutdown(socket.SHUT_WR) which sends a FIN signal instead of conn.close() which sends a RST signal.
We don't want to force the connection to close. TCP setup is expensive, so the browser would ask the server to keep the connection alive to query assets, and in this example the browser asks for style.css.
RST confuses the browser, and Firefox will show you "connection reset" error.
FIN says: "I finished talking to you, but I'll still listen to everything you have to say until you say that you're done."
RST says: "There is no conversation. I won't say anything and I won't listen to anything you say."
from FIN vs RST in TCP connections
Here is the Wireshark capture of using shutdown, we see that both the server at 3000 and the browser acknowledged each other's FIN.
When using close, we see that
A better option would be to wait for the client to initiate the 4 way finalization by programming the server to shut down the socket when the client signals FIN.
The 4 way finalization
From https://www.geeksforgeeks.org/tcp-connection-termination/
I'm new to this whole shazam and I'm a little confused. I want to have a server receive data on my computer, and a friend send data on his own computer. The code for my server is as follows:
import socket
HOST = 'HOST'
PORT = PORT
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)
I've blanked out the host ip and the port but I'm not really sure which one I'm supposed to be using for either tbh. The client code goes as follows
import socket
HOST = 'HOST'
PORT = PORT
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))
So my server receives it only when I run the client, not my friend. My question is what IP and ports am i supposed to use? Where can i find these numbers? Why does it only work when I run the client and how can I fix this? And if anybody can direct me to some resources about this topic I don't know what to search up :(
Thanks in advance!
The server should bind to the IP address of whatever interface it expects to receive traffic on. If it might receive traffic on multiple interfaces, you could bind to 0.0.0.0, which means 'all interfaces'. Whatever IP you decide on is what you should set for the server HOST value. For the server port, it could be a specific port or any port (port 0). Just be aware that the client will need to know which port the server is listening on.
The client should connect to the IP address or hostname and port of your server whose address is publicly accessible. This really depends on the network setup.
I suggest having your client connect to the same network as your server and trying again. If it doesn't work, make sure you're server is listening on 0.0.0.0.
If you are on different networks, these networks need to be bridged in some way.
I am trying to implement socket programming and want to configure the communication port number for both the server and client to a specific port. I specify the same port number on both the the client and server side but still when the program run's it takes a random port number. How do I fix the port number/make it static?
Server Side Code
import socket
s=socket.socket()
port=12345
s.bind(("192.168.0.111",port))
s.listen(5)
while True:
c, addr = s.accept()
print("got connection from ",addr)
sendingMessage = "Thank you for connecting"
c.send(bytes(sendingMessage, 'UTF-8'))
data = c.recv(16)
receivedData=data.decode("utf-8","ignore")
print (receivedData)
c.close()
if receivedData=="stop":
break
Client Side Code
import socket
port=12345
s=socket.socket()
s.connect(("192.168.43.111",port))
sendingMessage = input("Enter your message : ")
s.send(bytes(sendingMessage, 'UTF-8'))
data = s.recv(32)
receivedData=data.decode("utf-8","ignore")
print (receivedData)
s.close
If you want the client side to also use port 12345, you must also bind the client side port number. The port number given in the s.connect is the remote port to which you're connecting. IOW, your code should look something like this in the client:
s = socket.socket()
s.bind(('', port))
s.connect(("192.168.43.111", port))
You can also specify an IP address in the bind but typically you don't need to as the local IP address will be established by the route to the remote host.
I am trying to setup a very simply sockets app. My server code is:
import socket
s = socket.socket()
host = socket.gethostname()
port = 1234
s.bind((host,port))
s.listen(5) #Here we wait for a client connection
while True:
c, addr = s.accept()
print "Got a connection from: ", addr
c.send("Thanks for connecting")
c.close()
I placed this file on my remote Linode server and run it using python server.py. I have checked that the port is open using nap:
PORT STATE SERVICE
22/tcp open ssh
80/tcp open http
1234/tcp open hotline
I now run the client.py on my local machine:
import socket # Import socket module
s = socket.socket() # Create a socket object
port = 1234 # Reserve a port for your service.
s.connect(("139.xxx.xx.xx", port))
print s.recv(1024)
s.close # Close the socket when done
However I am not getting any kind of activity or report of connection. Could someone give me some pointers to what I might have to do? Do I need to include the hostname in the IP address I specify in the client.py? Any help would be really appreciated!
I've just summarize our comments, so your problem is this:
When you trying to using the client program connect to the server via the Internet, not LAN.
You should configure the
port mapping on your router.
And however, you just need configure the
port mapping for your server machine.
After you did that, then you can use the client program connect to your server prigram.
I'm trying to make simple Client-Server program but it's only working when I'm running both scripts on same computer, when moving it to other computer - It does not make connection at all.
Server:
__author__ = 'user-pc'
import socket # Import socket module
s = socket.socket() # Create a socket object
host="0.0.0.0" # Bind with everyone
port = 13254 # 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:
__author__ = 'user-pc'
import socket # Import socket module
s = socket.socket() # Create a socket object
host = "192.168.10.4" # Server Ip
port = 13254 # Reserve a port for your service.
s.connect((host, port))
print s.recv(1024)
s.close # Close the socket when done
Can you please help me to figure the problem?
Thanks.
As it works when you run both scripts on the server it is likely your port is closed.
Verify your port is open. Go to this website: http://www.canyouseeme.org/
Enter your port and IP. It is highly likely your port is closed. This will verify that. Assuming your port is open you need to look into your firewall settings as reccomended by dmg in the comment above. Then, it is no longer a python issue!