SOCKET PROGRAMMING PYTHON- Putting the server code on an online server - python

So I have a Client - Server code in python and its running perfectly on LAN. I have this server setup on AWS and I have uploaded my server code there. In my client code, I have changed the host to the ip-address of the server online.
Unfortunately when I run the server code then the client code, there is no connection established. What could be the issue ??
Here is a part of client code:
def starting_client():
sckt = socket.socket()
host = '172.31.32.226'
port = 9090
sckt.connect((host, port))
while True:
data = sckt.recv(1024) #Data received from the server
try:
Here is part of Server code:
def SeverSocket():
try:
global host
global port
global sckt
host = ''
port = 9090
sckt = socket.socket()
except socket.error as scktCreationErrorMsg:
print(f"An error was encountered during Socket Creation: {scktErrorMsg}")
else:
print("\033[34mSocket was created as succesfull\033[0m")

Related

Connect to server using python on AWS

Hobbyist. Going through Lutz's 'Programming Python' on sockets/servers. Intermediate level of python knowledge but almost no knowledge of network programming.
The first example runs a server and client scripts that I can get running on my own pc using 'localhost', but I would like to run the server on a remote machine.
I set up an AWS account and an instance of EC2 and an instance of Cloud 9.
The terminology for the different web services gets too confusing for me from here. I tried playing around with permissions on the security groups page, and I can get the script running on Cloud 9, but I can't connect to it from my PC.
If someone could please steer me in the right direction (how do I get this script running via AWS and how do allow external connections to the server to interact with it?) I would be most appreciative!
Thanks.
Server script.
from socket import *
myHost = ''
myPort = 50007
sockobj = socket(AF_INET, SOCK_STREAM)
sockobj.bind((myHost, myPort))
sockobj.listen(5)
while True:
connection, address = sockobj.accept()
print('Server connected by', address)
while True:
data = connection.recv(1024)
if not data: break
connection.send(b'Echo=>' + data)
connection.close()
Client script
import sys
from socket import *
# will change localhost to server IP address, right?
serverHost = 'localhost'
serverPort = 50007
message = [b'Hello network world']
if len(sys.argv) > 1:
serverHost = sys.argv[1]
if len(sys.argv)> 2:
message = (x.encode() for x in sys.argv[2:])
sockobj = socket(AF_INET, SOCK_STREAM)
sockobj.connect((serverHost, serverPort))
for line in message:
sockobj.send(line)
data = sockobj.recv(1024)
print('Client received:', data)
sockobj.close()

Python | Connecting to a remote server using sockets

recently I've been messing around with sockets in python and i needed to connect to a remote server for a project. I know there are plenty of questions about this topic but none of the solutions worked for me and i am about to go mad if i can't get this to work.
Server code:
import socket
import threading
FORMAT = "UTF-8"
PORT = 55555
SERVER = ''
ADDR = ('0.0.0.0', PORT)
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
def handle_client(conn, addr):
print(f"[NEW CONNECTION] {addr} connected.")
conn.send("Test".encode(FORMAT))
def start():
server.listen()
print(f"[LISTENING] Server is listening on {PORT}")
while True:
connection, adress = server.accept()
thread = threading.Thread(target=handle_client, args=(connection, adress))
thread.start()
print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}")
print("[STARTING] server is starting...")
start()
Client Code:
import socket
import threading
FORMAT = "UTF-8"
PORT = 55555
SERVER = "xx.xxx.xxx.xxx" # public ip
print(f"\nconnecting... {PORT}\n")
ADDR = (SERVER, PORT)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
client.connect(ADDR)
except:
print("Couldnt connect.")
print(client.recv(1024).decode(FORMAT))
When i change the SERVER variable in client script to my local ip (192.168.1.34), i can run these two scripts in two different pcs in the same LAN and it works well, i recieve the "Test" message in my client pc.
However, when i change the SERVER variable to my public ip and run the server in my server pc, i can't connect to the client pc. Here, my server and client pcs are NOT in the same network. Server is connected to my router whereas client is in another network. When i run the client script nothing happens and after a while i get [WINERROR 10057]
I've done port forwarding to port 55555. I tried disabling all firewalls and even creating a new rule in windows firewall to allow connections from port 55555. It still doesn't work and i can't figure out why.
If there is anyone who can see the problem here i would really appreciate it.
The only thing I can see that maybe is causing a problem is in your ADDR variable. I recently did a similar project that was successful, and in my sever code I did the equivalent of:
ADDR('',PORT)
I don't know for sure this would fix your problem, but it is my best guess from the info you provided.

python socket server in Heroku

Im trying to deploy a server using the socket module to heroku. The server runs correctly when I look at the logs from heroku, the problem is that i have not been able to connect to it with the client and it seems that an ip address is constantly connecting to the server.
Procfile: web: python Server.py
The server I built has this structure.
import socket
import os
from _thread import start_new_thread
PORT = int(os.environ(['PORT']))
HOST = '0.0.0.0'
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
s.bind((HOST, PORT))
except socket.error as e:
pass
s.listen(2)
def threaded_client(conn):
print(f'CONNECTED -> {conn}')
while True:
# some logic
pass
if __name__== '__main__':
while True:
conn, addr = s.accept()
start_new_thread(threaded_client, (conn,))
And the client.
import socket
PORT = 80
HOST = 'https://my-heroku-app.herokuapp.com'
client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client.connect((HOST,PORT))
I have a similar issue as the one mentioned in here
Any insight would be appreciated. Thanks
you can't use heroku to host a tcp server ,you need a service like linode https://www.linode.com/ ,or aws ,but you can use heroku to host a websocket server which you can use a python websocket client to connect to ,like so
from websocket import create_connection
ws = create_connection("ws://myapp.herokuapp.com")
print("Sending 'Hello, World'...")
ws.send("Hello, World")
print("Sent")
print("Receiving...")
result = ws.recv()
print("Received '%s'" % result)
ws.close()

Socket server in python refuses to connect

I am trying to create a simple web server with python using the following code.
However, When I run this code, I face this error:
ConnectionRefusedError: [WinError 10061] No connection could be made
because the target machine actively refused it
It worths mentioning that I have already tried some solutions suggesting manipulation of proxy settings in internet options. I have run the code both in the unticked and the confirmed situation of the proxy server and yet cannot resolve the issue.
Could you please guide me through this ?
import sys
import socketserver
import socket
hostname = socket.gethostname()
print("This is the host name: " + hostname)
port_number = 60000
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
soc.connect((hostname,port_number))
Standard EXAMPLE of socket connection
SERVER & CLIENT
run this in your IDLE
import time
import socket
import threading
HOST = 'localhost' # Standard loopback interface address (localhost)
PORT = 60000 # Port to listen on (non-privileged ports are > 1023)
def server(HOST,PORT):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
while True:
conn, addr = s.accept()
data = conn.recv(1024)
if data:
print(data)
data = None
time.sleep(1)
print('Listening...')
def client(HOST,PORT,message):
print("This is the server's hostname: " + HOST)
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
soc.connect((HOST,PORT))
soc.send(message)
soc.close()
th=threading.Thread(target = server,args = (HOST,PORT))
th.daemon = True
th.start()
After running this, in your IDLE execute this command and see response
>>> client(HOST,PORT,'Hello server, client sending greetings')
This is the server's hostname: localhost
Hello server, client sending greetings
>>>
If you try to do server with port 60000 but send message on different port, you will receive the same error as in your OP. That shows, that on that port is no server listening to connections

Python local UDP client won't accept messages from local server when using hostname

I'm following the book "Foundations of Python Network Programming". It has an example of a UDP server/client that can send messages to each other. Here is what it looks like
import socket, sys
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
MAX = 65535
PORT = 1060
if 2<= len(sys.argv) <=3 and sys.argv[1] == 'server':
interface = sys.argv[2] if len(sys.argv) > 2 else ''
s.bind((interface, PORT))
print('Listening at {}'.format(s.getsockname()))
while True:
data, address = s.recvfrom(MAX)
print('The client at {} says: {}'.format(address, repr(data)))
msg = 'Your data was {} bytes'.format(len(data))
s.sendto(msg.encode('utf-8'), address)
elif len(sys.argv)==3 and sys.argv[1]=='client':
hostname = sys.argv[2]
s.connect((hostname, PORT))
print('Client socket name is {}'.format(s.getsockname()))
s.send(b'This is another message')
s.settimeout(5.0)
data = s.recv(MAX)
print('The server says', repr(data)) code here
I start the server on my local machine:
python listing2-2.py server
Listening at ('0.0.0.0', 1060)
Then I run my client
python listing2-2.py client 127.0.0.1
Client socket name is ('127.0.0.1', 59535)
The server says b'Your data was 23 bytes'
And everything is fine. I can use localhost and that works too. But if I use my hostname
python listing2-2.py client <myhostname>
Client socket name is ('127.0.0.1', 45677)
and the client times out. The server receives the message from the client (I see the output "This is another message" on the server side), but the client seems to be refusing the message from the server. I'm trying to understand why.

Categories

Resources