I have an azure vm running Linux (ubuntu 18.04) LTS and i have created a python socket server binding a socket with
socket.bind(('localhost', 10000))
but when i try to connect from another script via
socket.connect(ip,10000)
the server reject the connection.
How do i solve this?
I already tried to open the port on my wm with
az vm open-port --resource-group myResourceGroup --name myVM --port 10000
But the server still refuse my connection.
Client script:
import socket
import threading
class Client:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def sendData(self):
while True:
self.sock.send(bytes(input("")))
def __init__(self):
self.sock.connect(('serverip', 10000))
iThread = threading.Thread(target=self.sendData)
iThread.daemon = True
iThread.start()
while True:
data = self.sock.recv(1024)
if not data:
break
print(data)
client = Client()
Server script:
import socket
import threading
import random
def getuserdata(b):
#function that works
return a
class Server:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connections = []
def __init__(self):
self.sock.bind(('localhost', 10000))
self.sock.listen(1)
print (self.sock.getsockname())
def handler(self, c , a):
while True:
try:
data = c.recv(1024)
except:
self.connections.remove(c)
c.close()
print(str(a[0]) + ":" + str(a[1]), "disconnected")
print("lobby has " + str(len(self.connections)) + " players connected")
break
#loop per client
#for connection in self.connections:
# connection.send(data)
def run(self):
while True:
if len(self.connections) < 8:
c , a = self.sock.accept()
cThread = threading.Thread(target=self.handler , args=(c,a))
cThread.daemon = True
cThread.start()
self.connections.append(c)
print(str(a[0]) + ":" + str(a[1]) , "connected")
print("lobby has " + str(len(self.connections)) + " players connected")
#loop del server
else:
break
print("lobby piena")
list= getuserdata(8)
for index, player in enumerate(self.connections):
player.send(bytes(list[index]))
while True:
pass
server = Server()
server.run()
Please use 0.0.0.0
or the IP address of your Azure Ubuntu VM instead of localhost
as server socket bind host.
If you use localhost
as host bind by socket server, then just only client on the same machine can connect to your server, because localhost
means 127.0.0.1
which only allow client connect to the server IP address 127.0.0.1
.
Meanwhile, you need to refer to the offical documents Tutorial: Create and manage Azure virtual networks for Linux virtual machines with the Azure CLI
or How to open ports to a virtual machine with the Azure portal
to add an inbound rule in the NSG setting of networking via Azure CLI or on portal.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.