I want to make server (for multiplayer game), but I can't connect to my pc through my public IP address.
My server is programmed in Java like this:
int port = 60000;
int client_num = 0;
ClientHandler clientHandler;
try (ServerSocket serverSocket = new ServerSocket(port)) {
System.out.println("Server is listening on port " + port);
while (true) {
Socket client = serverSocket.accept();
System.out.println("New client connected: "+client);
}
} catch (IOException ex) {
System.out.println("Server exception: " + ex.getMessage());
ex.printStackTrace();
}
Client is programmed in javascript like this(I am using websockets):
var websocket = new WebSocket(
'ws://127.0.0.1:60000');
websocket.onopen = function () {
$('h1').css('color', 'green');
websocket.send("Hello");
$('h1').css('color', 'purple');
};
You can see, that I use the same port (60 000) in both-server and client. In client where I write IP address (ws://127.0.0.1) I can write localhost(127.0.0.1) or my private ip (192.168.0.100) - AND IT WORKS! But when I write there my public ip (something like 91...***), it dont work and server dont write message "New client connected:" (like in case of local host do)... So I thought that problem is in port forwarding. But I tried to port forward, as you can see in image:
But it still don't work. I also tried to use DMZ in my router. Same results. I also tried to turn off firewall and web shield of my anitivirus. Again same result...Even if i try to check if my port 60 000 is open with some online test (https://www.yougetsignal.com/tools/open-ports/) it say that my port is closed...So why it don't work?
I have found out, that even if I turn on Apache which listen on ports 80 and 443, tools for checking open ports also show me this ports (80 and 443) as closed (even when I turn DMZ on my router)...WHY?
Note: I am sure, that i use right local IP for setting up port forwarding and DMZ, I use IP which give me ipconfig(and also as I already wrote - client-server communication works when I use this local address (192.168.0.100) of my pc where server runs...)
Please help me! :)
Your issue is about networking and network routing. Try to connect to your server from the outside of your local network. Somewhere from internet. Buy a VPS or ask your friend. First of all you can check your port is opened using nmap. If it were opened you are able to connect to your server. Otherwise it might be your D-LINK problem. I see you have 22 port forwarding already. When I used D-LINK DIR-600 router I have similar issue - port was adjusted correctly but I was not able to connect via opened port. And I could fix this issue only by using DD-WRT - unofficial firmware.
Related
I have created a flask website with python. Now, I'm trying to implement some WebRTC/PeerToPeer functionality. I have managed to connect the two peers by manually copy/pasting the SDP back and forth between them using input fields. Everything is working as supposed.
In stead of manually copy/pasting the SDP back and forth, I want to send the SDP through a websocket from the (vanilla) javascript client side to the python backend. However, this is causing me some issues.
I'm not sure I totally understand how the communication between sockets work (I'm fairly new in that field). The code below is my python server.
import socket
import threading
HEADER = 8192
PORT = 3000
SERVER = '{PRIVATE IP ADDRESS}'
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = '!DISCONNECT'
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
def handle_client(conn, addr):
print(f'[NEW CONNECTION] {addr} connected.')
connected = True
while connected:
msg = conn.recv(HEADER)
print(f'[{addr}] {msg}')
conn.close()
def start():
server.listen()
while True:
conn, addr = server.accept()
thread = threading.Thread(target=handle_client, args=(conn, addr))
thread.start()
print(f'[ACTIVE CONNECTIONS] {threading.activeCount() - 1}')
if threading.activeCount() - 1 == 0:
break
start()
In the javascript on the client side, all I do is initialize the websocket using the same IP and port as the server is running on. When I refresh the client html page in the browser, the client socket is sending a message to the server. However, I'm not able to decode this message with utf-8 because of a wrong startbyte or something. I have read that sockets might use different protocols. Does that have anything to say in this case? Also, the javascript websocket never changes readystate from 0 to 1, so it never actually connects.
Am I missing something? Is there an easier or better way to connect the javascript client with the python server?
I barely ask any questions on Stack Overflow, but this one is beyond me. I guess I'm missing something basic as I'm pretty new to Node server.
Our application is pretty basic. The server is supposed to receive a handful of text lines (data), merge and parse them, and once the connection is closed (data sending is over) it sends the data to the api.
var net = require('net');
var fs = require('fs');
const axios = require('axios')
const server = new net.Server();
server.listen(PORT, IP);
server.on("connection", client => {
client.write("Hello\n");
console.log('connected');
let received = "";
client.on("data", data => {
received += data
console.log("Partial data is: " + data);
});
client.on("close", () => {
received = received.toString('utf8');
fs.appendFile('log.txt', received, function (err) {});
received = received.replace(/(?:\r\n|\r|\n)/g, "||");
axios.post(APIADDRESS, {data: received});
console.log('Full data is: '+ {data: received});
});
});
To send the data I'm simply running a netcat or nc using the netcat ipaddress port, that's not a problem. It's connecting fine, status message is received.
The thing is - once I open two or more connections from two DIFFERENT SSh servers something weird happens. I can send the line after line just fine. The server reports back "partial data" debug without problem, for both of them.
However, once I close one of the connections (ctrl+c) they BOTH close.
In the end, only the data from the manually closed connection is received. The other one, from a separate nc on a separate ssh server never reaches the client.on("close") part, it seems. It's just terminated for no reason.
Any ideas? I don't even know where to start.
//EDIT
Just tested it from my pc and some ssh mobile app using separated SSH servers. As soon as ctrl+c is sent at any device it closes the connection for all clients.
//Forgot to mention I'm running pm2 to keep the server up. Once I turned on the script by hand, ignoring pm2 - it works fine. Weird. It is happening because of PM2.
I would guess that you have Putty configured to ‘Share SSH connections if possible’. Per some doc, when doing so:
When this mode is in use, the first PuTTY that connected to a given server becomes the ‘upstream’, which means that it is the one managing the real SSH connection. All subsequent PuTTYs which reuse the connection are referred to as ‘downstreams’: they do not connect to the real server at all, but instead connect to the upstream PuTTY via local inter-process communication methods.
So, if you Ctrl+C the PuTTY session that is managing the actual shared connection, they both lose their connection.
You could presumably disable this shared connection feature at either the client or server end of things since both must be enabled for sharing to occur.
To anyone coming here in the future.
If you are using pm2 with --watch enabled and the text log file is in the same folder as your main server script... That's the reason why it drops the connection after a single client disconnects. It just detects that the log has changed.
I'm not facepalming, that's not even funny.
I have started an MQTT server just like this example.
This code is hosted in an ASP.Net Core 2.0 application but I have tried console application with no luck.
I have also setup a client using the same demo as above and it connects perfectly. Also an Android client connects fine. But I have placed a MQTT.js client webpage but it will not connect with chrome showing net::ERR_CONNECTION_REFUSED error.
I believe that the problem is with server not supporting web sockets. Because if I start my client with WS type it will not connect.
var options = new MqttClientOptions
{
Server = "localhost",
//ConnectionType = MqttConnectionType.Tcp // Connects
ConnectionType = MqttConnectionType.Ws // Does not connect
};
Now MQTT.js supports TCP as far this link is telling. But I don't seem to be able to work it.
This is the code in my page javascript:
var client = mqtt.connect('tcp://localhost') //Also did mqtt://localhost
client.on('connect', function () {
client.subscribe('myTopic')
client.publish('myTopic', 'Hello mqtt')
})
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString())
client.end()
})
I want to know how can I make javascript MQTT client to use TCP? (Any other js plugin maybe?) Or alternatively how can I enable WebSockets in MQTTNet.
Thanks for your help.
MQTT.js does support both native MQTT and MQTT over Websockets, but if you are embedding it in to a web app it can only use MQTT over Websockets because the browsers sandbox will not allow it to use arbitrary TCP connections.
As for enabling Websockets in the broker I can't see anything obvious in the code so you'll probably have to raise and issue against the github project to ask for details.
The next version of MQTTnet (2.5) will have support for WebSocket connections for the server via AspNetCore 2.0.
I need to send data out from my google assistance app to a database. In order to do this, I've created a server that takes the data, packages it, and then sends it out. I have the hostname and port and it works in a normal javascript/node.js program but when I use it in my google assistant app nothing happens. I tried figuring out the problem and it looks like the code just isn't connecting. The code I'm using to send data to the server is as follows:
function sendData(app){
var net = require('net');
var message = {"test": 200};
var thisMessage = JSON.stringify(message);
var client = new net.Socket();
client.connect(<port>, '<hostname>', function() {
app.tell(JSON.stringify(client.address()));
console.log('Connected');
client.write(thisMessage);
});
client.on('data', function(data) {
console.log('Received: ' + data);
client.destroy();
});
client.on('close', function() {
console.log('Connection closed');
});
return 0;
}
(NOTE: Port and hostname left out for privacy purposes)
This completely skips over the app.tell, leading me to believe the connection is never made. I know it works asynchronously with the server, however, I don't understand why it isn't connecting whatsoever.
I have tried it both in simulation and on my smartphone with sandbox on and off. Is there a better way to connect? Note that the server I'm connecting to is python-based.
The problem is likely that you're running it on Cloud Functions for Firebase which has a limit on outbound connections under their free "Spark" plan. With this plan, you can only connect to other Google services. This is usually a good way to start understanding how to handle Action requests, but has limitations. To access endpoints outside of Google, you need to upgrade to either their "Flame" fixed price plan or "Blaze" pay-as-you-go plan.
You do not, however, need to run on Google's servers or need to use node.js. All you need is a public HTTPS server with a valid SSL cert. If you are familiar with JSON, you can use any programming language to handle the request and response. If you are familiar with node.js, you just need a node.js server that can create Express request and response objects.
I'm running a Go webserver using Gorilla/websocket for a real-time chess/chat application. As far as I know, I define the address and port in two locations, the Go http.ListenAndServer() method and the Javascript new Websocket(); function. This works great accross browsers on the same host machine, but it gets tricky when trying to extend the functionality over my internal network. So I use, for instance:
Go:
PORT := "0.0.0.0:8080"
// ...
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
h.serveWs(hub, w, r) // h is a chessboard Handler wrapper
})
//...
http.ListenAndServe(PORT, nil)
Javascript:
conn = new WebSocket("ws://0.0.0.0:8080/ws");
In my effort to get this working on different devices over the network I've tried using, instead of the 0.0.0.0 address, localhost or my hostname and my host's internal ip (e.g.) 10.232.44.20; With the latter, the internal ip hardcoded in, it works, but the other attempts don't. I thought that using 0.0.0.0 would accept all connections from within the network, which I gathered from this answer:
What is the difference between 0.0.0.0, 127.0.0.1 and localhost?
How should I program ListenAndServe as well as new Websocket so that I can access the server within the internal network, without having to hardcode my internal ip address? Should I access that number programmatically from Js and Go? In the end, I want to be able to run this server on a variety of networks, without configuration, and have it just work. What am I missing?
If the web page and websocket endpoints are served by the same host, then create the websocket using the host used to fetch the web page:
conn = new WebSocket("ws://" + window.location.host + "/ws");
This will just work in all network configurations.
As far as the Go code is concerned, the easiest approach is to listen on all networks:
if err := http.ListenAndServe(":8080", nil); err != nil {
// handle error
}