simple server/client program get error : java.net.ConnectException: Connection refused - java

i try to write simple messenger look like it's example in book(Java How To Program 9th Edition Paul Deitel Harvey Deitel, part 27.6). after i finished , i try to test it. it work on localhost(127.0.0.1), also work on computer which connect same modem (i mean ips such 192.168.0.1 and etc) but when i want to test it on some computer cross the internet a client side code got connection refused error.
i think when i client(which is my friend in somewhere in my city) try to connect server(which is me, again some where in city), when he enter my ip to connect me he connect to my modem and my modem don't send it's information to me(it's hard to explain something that u can't deeply understand it in none mother language so i'm sorry at all )
any help is important to me.
here is server code
//:D
//hello every Body:! this is my first program which use some networks !!! :-khatkeif
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.ServerSocket;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.io.EOFException;
public class Server extends JFrame
{
JTextField enteredText;//input message from user
JTextArea displayArea;//display information to user
ObjectInputStream input;//input object from cilent
ObjectOutputStream output;//output Object to client
ServerSocket server;//server Socket
Socket connection;//connecton to cilent
public Server()//constructor
{
super("Server");
setLayout(new BorderLayout(5,5));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new JLabel("Server Messenger"),BorderLayout.NORTH);
enteredText= new JTextField("entered message here");
enteredText.setEditable(false);
enteredText.addActionListener(new TextHandler());
add(enteredText,BorderLayout.SOUTH);
displayArea= new JTextArea();
displayArea.setEditable(false);
add(new JScrollPane(displayArea),BorderLayout.CENTER);
setSize(500,500);
setVisible(true);
}
public void runServer()
{
try
{
server = new ServerSocket(12345,10);//create server Socket
while(true)
{
waitForConnection();//wait util a client want to connect
openStreams();//open streams for send/get data
processConnection();//recive message from client
}
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
public void waitForConnection() throws IOException
{
displayMessage("waiting for client");
connection=server.accept();//alow server for connection
displayMessage("connect to "+connection.getInetAddress().getHostName());
}
public void openStreams() throws IOException//open stream that help me to send and recive message
{
displayMessage("setting I/O");
output= new ObjectOutputStream(connection.getOutputStream());//create output to send message
output.flush();//send headers to client
input = new ObjectInputStream(connection.getInputStream());//create input from client message
displayMessage("Got I/O");
}
public void processConnection() throws IOException//recive message from client & alow server to send message to client
{
try
{
displayMessage("connected successfully");
setTextEditable(true);//alow server to send message to client
String reciveMessage = (String)input.readObject();//recive message form client
while(!reciveMessage.equals("TERMINATE"))//if client send this string,make process connection finish
{
displayMessage(connection.getInetAddress().getHostName()+">>> "+reciveMessage);//display clinet message in display erea
reciveMessage=(String)input.readObject();//read next message
}
}
catch(ClassNotFoundException cnfe)
{
cnfe.printStackTrace();
}
displayMessage(connection.getInetAddress().getHostName()+" disconnect`");
close();
}
public void close() throws IOException//close every thing
{
sendMessage("TERMINATE");
input.close();
output.close();
connection.close();
setTextEditable(false);
displayMessage("connection terminated");
}
public void setTextEditable(final boolean val)//set text field editable
{
SwingUtilities.invokeLater
(
new Runnable()
{
public void run()
{
enteredText.setEditable(val);
}
}
);
}
public void displayMessage(final String message)//display message in displayArea
{
SwingUtilities.invokeLater(
new Runnable()
{
public void run()
{
displayArea.append(message+"\n");
}
}
);
}
public void sendMessage(String message) throws IOException//send message to client
{
output.writeObject(message);
output.flush();
displayMessage("Me>>> "+message);
enteredText.setText("");
}
private class TextHandler implements ActionListener//when user press enter a text in enteredText send to client
{
public void actionPerformed(ActionEvent ev)
{
try
{
sendMessage(ev.getActionCommand());
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
}
and it's main
//:D
public class ServerRun
{
public static void main(String[] args)
{
Server server = new Server();
server.runServer();
}
}
let's go for client code :D
//:D
//this is client side
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.InetAddress;
public class Client extends JFrame
{
JTextField enteredText;//user input message
JTextArea displayArea;//display information
ObjectOutputStream output;//send message to server
ObjectInputStream input;//recive message from server;
Socket connection;//connection to server
String serverInfo;//server name
JButton closeB;
JPanel downPanel;
public Client ()
{
super("Client");
setLayout(new BorderLayout(5,5));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new JLabel("Client Messenger"),BorderLayout.NORTH);
enteredText= new JTextField("Enter message Here");
setTextEditable(false);
enteredText.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent ev)
{
try
{
sendMessage(ev.getActionCommand());
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
);
closeB= new JButton("close");
closeB.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent ev)
{
try
{
close();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
);
downPanel= new JPanel(new BorderLayout(5,5));
downPanel.add(enteredText,BorderLayout.CENTER);
downPanel.add(closeB,BorderLayout.EAST);
add(downPanel,BorderLayout.SOUTH);
displayArea= new JTextArea();
displayArea.setEditable(false);
add(new JScrollPane(displayArea),BorderLayout.CENTER);
setSize(500,500);
setVisible(true);
}
public void runClient(String host)//run client program
{
try
{
connectToServer(host);
openStreams();
processConnection();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
public void connectToServer(String host) throws IOException//connect to server
{
displayMessage("connceting to " + host);
connection = new Socket(InetAddress.getByName(host),12345);//create connection to server
}
public void openStreams() throws IOException // open streams for recive/send messages
{
output= new ObjectOutputStream( connection.getOutputStream());//create output for send messages
output.flush();//send headers
input = new ObjectInputStream(connection.getInputStream());//create input for recive messages
displayMessage("connected to "+connection.getInetAddress().getHostName());
}
public void processConnection()throws IOException //recive message util server trminate
{
try
{
setTextEditable(true);//alow user to send message
String reciveMessage=(String) input.readObject();
while(!reciveMessage.equals("TERMINATE"))
{
displayMessage(connection.getInetAddress().getHostName()+">>> "+reciveMessage);
reciveMessage=(String)input.readObject();
}
displayMessage("connection lost");
}
catch(ClassNotFoundException cnfe)
{
displayMessage("server message is not clear");
}
}
public void close() throws IOException//close every thing
{
sendMessage("TERMINATE");
input.close();
output.close();
connection.close();
System.exit(0);
}
public void sendMessage(String message) throws IOException//send message to server
{
output.writeObject(message);//send message to server
output.flush();//send headers
displayMessage("Me>>> "+message);//displate sent message to user
enteredText.setText("");
}
public void displayMessage(final String message)
{
SwingUtilities.invokeLater(
new Runnable()
{
public void run()
{
displayArea.append(message+"\n");
}
}
);
}
public void setTextEditable(final boolean val)
{
SwingUtilities.invokeLater(
new Runnable()
{
public void run()
{
enteredText.setEditable(val);
}
}
);
}
}
and it's main :
//:D
import javax.swing.JOptionPane;
public class ClientRun
{
public static void main(String args[])
{
Client client = new Client();
client.runClient(JOptionPane.showInputDialog(null,"please enter host IP:"));
}
}
again thanks

Preface: This is most likely not a problem with your code, but rather a problem with your network setup. (Looks like #dimoniy beat me to answering, hopefully this sends the same idea as his).
The most likely reason that your friend cannot connect to your server is because he cannot get through your modem. In order for someone to connect to your server (from the code the port looks to be 12345) you need to change some settings in your router/modem (Which you can usually connect to by going to 192.168.1.1 or 192.168.0.1) and adding a "Port forwarding rule". This will allow connections "outside" of your network (aka the rest of the world) to connect to the server on that port.
You will need to add a 'Port Forwarding' rule to your modem/router that redirects all the traffic on port 12345 to the local ip of where you are hosting the server (your computers ip; found by ipconfig or ifconfig cmd in console/terminal). Then you will need to get your 'External IP' which can be found by Googling "what's my ip". This is the "address" of your network to the rest of the world. This is the IP that you need to give to your friend.
Your friend needs to use your External IP that you gave him, along with the port that the server is running on, and your router should forward his connection to your server and should work!
Some topics you might want research some more are: "external IP vs internal IP" and "Port Forwarding".
Hope this helps!

The problem is that you're trying to access a computer which does not have a public IP. The only thing that has "real" IP address is your router or cable modem (depending on the configuration). In order for remote computer to access the computer where the server is running you best option would be to set up port forwarding for the server port that you use (12345) and make sure that the traffic gets redirected to your machine.
The ways to set up port forwarding are different for different routers, you'll have to google your router and phrase "port forwarding".
Once everything set up the client will have to use the router's public IP address (you can look this up in your router settings). Then it will go like this: client will hit the router, router will forward the traffic to your local computer and your server socket then should do it's thing. Once the connection is established you should be good to go.
Hope that helps.

Related

how to open a port entered by user java

I have two doubts
FIRST.
I am creating a desktop application in netbeans, I want to open a port entered by user.I have created two files in same package, getting port number from user its in one file and processing on it is second file.
I have created object of that class for getting user's entered port number its not showing any error but port is not opening on that number i have checked using tcp view
here is code of first file
Server.java
package server;
import java.io.*;
import java.net.*;
import javax.swing.JFrame;
public class Server extends Thread {
public static int SERVERPORT;
private boolean running = false;
public volatile boolean stop = false;
public Socket client = null;
public static void main(String[] args) {
mainFrame frame = new mainFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
SERVERPORT = frame.portnum;//here i am getting port number from 2nd file
}
#Override
public void run() {
super.run();
running = true;
try {
System.out.println("Server Has Started........ \n Waiting for client........");
ServerSocket serverSocket = new ServerSocket(SERVERPORT);
try {
while (!stop && running) {
client = serverSocket.accept();
System.out.println("Connection Accepted......");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String usercmnd = in.readLine();
if (usercmnd != null) {
Runtime runtime = Runtime.getRuntime();
Process p = runtime.exec(usercmnd);
}
}
here is 2nd file where user have to enter a port number
mainFrame.java
package server;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.net.*;
//import server.Server;
/**
*
* #author admin
*/
public class mainFrame extends JFrame {
private Server mServer;
public int portnum;
public mainFrame() {
super("mainFrame");
mServer = new Server();
initComponents();
setIcon();labInfo.setText("Not Connected");
try{ ipAdd.setText(String.valueOf(InetAddress.getLocalHost().getHostAddress()));
}catch(Exception e){labInfo.setText(e.getMessage());}
}
private void connActionPerformed(java.awt.event.ActionEvent evt) {
if(port.getText().equals(""))
{
labInfo.setText("Port number cannot be empty!!");
}else{
portnum=Integer.parseInt(port.getText());//here i am getting user's entered port number
conn.setEnabled(false);port.setEditable(false);
labInfo.setText("Waiting for Connection.....");
mServer.start();
}
}
private void disconnActionPerformed(java.awt.event.ActionEvent evt) {
mServer.requestStop();
labInfo.setText("Not Connected");
port.setEditable(true);
conn.setEnabled(true);
}
SECOND.
Is there any way to check entered port number is currently using so then we can alert the user to use another port number...???
I would rather suggest you run the mainFrame class first from which you can call the Server class at the click of the Button to retrieve the port number entered in the TextField. I can't seem to help with the full code but you can change your connActionPerformed() method to
private void connActionPerformed(java.awt.event.ActionEvent evt) {
boolean success = false;
do {
try {
if (port.getText().equals("")) {
labInfo.setText("Port number cannot be empty!!");
} else {
portnum = Integer.parseInt(port.getText());//here i am getting user's entered port number
ServerSocket serverSocket = new ServerSocket(portnum);
System.out.println("Connected to Server");
mServer = new Server(serverSocket);//Which means you need to implement a constructor with a Server argument.
//conn.setEnabled(false);
//port.setEditable(false);
//abInfo.setText("Waiting for Connection.....");
mServer.start();
success = true;
}
} catch (BindException ex) {
System.out.println("Port in use");
}
} while (success);
}
And then you can implement a constructor like this:
ServerSocket serverSocket;
public Server(ServerSocket serverSoket){
this.serverSocket = serverSoket;
}
NOTE: since this code is not complete, manipulate to suit your needs.
Hope this would be helpful, thank you.

Netty server with open http connections limit

I'm new to Netty and I wrote based on an example I found a Netty http server, that keeps http connections open to send server-sent-events to the browser client.
Problem is that it only accepts up to about ~5 connections and after that blocks new connections. I googled and found most answers said to set SO_LOGBACK to a higher value. Tried different values and while I saw no difference. I even set it to MAX_INTEGER value and still had only 5 connections.
Server code (Using Netty version 4.1.6.Final):
package server;
import static io.netty.buffer.Unpooled.copiedBuffer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.HttpVersion;
public class NettyHttpServer {
private ChannelFuture channel;
private final EventLoopGroup masterGroup;
public NettyHttpServer() {
masterGroup = new NioEventLoopGroup(100);
}
public void start() {
try {
final ServerBootstrap bootstrap = new ServerBootstrap().group(masterGroup)
.channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer < SocketChannel > () {
#Override
public void initChannel(final SocketChannel ch) throws Exception {
ch.pipeline().addLast("codec", new HttpServerCodec());
ch.pipeline().addLast("aggregator", new HttpObjectAggregator(512 * 1024));
ch.pipeline().addLast("request", new ChannelInboundHandlerAdapter() {
#Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg)
throws Exception {
System.out.println(msg);
registerToPubSub(ctx, msg);
}
#Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
#Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.writeAndFlush(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
HttpResponseStatus.INTERNAL_SERVER_ERROR,
copiedBuffer(cause.getMessage().getBytes())));
}
});
}
}).option(ChannelOption.SO_BACKLOG, Integer.MAX_VALUE)
.childOption(ChannelOption.SO_KEEPALIVE, true);
channel = bootstrap.bind(8081).sync();
// channels.add(bootstrap.bind(8080).sync());
} catch (final InterruptedException e) {}
}
public void shutdown() {
masterGroup.shutdownGracefully();
try {
channel.channel().closeFuture().sync();
} catch (InterruptedException e) {}
}
private void registerToPubSub(final ChannelHandlerContext ctx, Object msg) {
new Thread() {
#Override
public void run() {
while (true) {
final String responseMessage = "data:abcdef\n\n";
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
copiedBuffer(responseMessage.getBytes()));
response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/event-stream");
response.headers().set(HttpHeaders.Names.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
response.headers().set("Cache-Control", "no-cache");
ctx.writeAndFlush(response);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
}.start();
}
public static void main(String[] args) {
new NettyHttpServer().start();
}
}
Client js code (I run it more than 5 times from my browser in different tabs, and the not all of them get:
var source = new EventSource("http://localhost:8081");
source.onmessage = function(event) {
console.log(event.data);
};
source.onerror= function(err){console.log(err); source.close()};
source.onopen = function(event){console.log('open'); console.log(event)}
You need to let the browser know that you are done sending the response, and for that you have three options.
Set a content length
Send it chunked
Close the connection when you are done
You aren't doing any of those. I suspect your browser is still waiting for the full response to each request you send, and is using a new connection for each request in your testing. After 5 requests your browser must be refusing to create new connections.
Another thing I noticed is that you are creating a new thread for each request in your server, and never letting it die. That will cause problems down the line as you try to scale. If you really want that code to run in a different thread then I suggest looking at overloaded methods for adding handlers to the pipeline; those should let you specify a thread pool to run them in.

Multiple messages on a Grizzly Websocket Connection

We are using Websockets from the Grizzly project and had expected that the implementation would allow multiple incoming messages over a connection to be processed at the same time. It appears that this is not the case or there is a configuration step that we have missed. To validate this I have created a modified echo test that delays in the onMessage after echoing the text. When a client sends multiple messages over the same connection the server always blocks until onMessage completes before processing a subsequent message. Is this the expected functionality?
The simplified server code is as follows:
package com.grorange.samples.echo;
import java.util.concurrent.atomic.AtomicBoolean;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.grizzly.http.server.NetworkListener;
import org.glassfish.grizzly.websockets.DataFrame;
import org.glassfish.grizzly.websockets.WebSocket;
import org.glassfish.grizzly.websockets.WebSocketAddOn;
import org.glassfish.grizzly.websockets.WebSocketApplication;
import org.glassfish.grizzly.websockets.WebSocketEngine;
public class Echo extends WebSocketApplication {
private final AtomicBoolean inMessage = new AtomicBoolean(false);
#Override
public void onClose(WebSocket socket, DataFrame frame) {
super.onClose(socket, frame);
System.out.println("Disconnected!");
}
#Override
public void onConnect(WebSocket socket) {
System.out.println("Connected!");
}
#Override
public void onMessage(WebSocket socket, String text) {
System.out.println("Server: " + text);
socket.send(text);
if (this.inMessage.compareAndSet(false, true)) {
try {
Thread.sleep(10000);
} catch (Exception e) {}
this.inMessage.set(false);
}
}
#Override
public void onMessage(WebSocket socket, byte[] bytes) {
socket.send(bytes);
if (this.inMessage.compareAndSet(false, true)) {
try {
Thread.sleep(Long.MAX_VALUE);
} catch (Exception e) {}
this.inMessage.set(false);
}
}
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.createSimpleServer("http://0.0.0.0", 8083);
WebSocketAddOn addOn = new WebSocketAddOn();
addOn.setTimeoutInSeconds(60);
for (NetworkListener listener : server.getListeners()) {
listener.registerAddOn(addOn);
}
WebSocketEngine.getEngine().register("", "/Echo", new Echo());
server.start();
Thread.sleep(Long.MAX_VALUE);
}
}
The simplified client code is:
Yes, it's expected.
The way to go is to pass message processing, inside onMessage, to a different thread.

java.net.connectexception connection timeout

hi i am using this codes for rmi
RmiServer.java
import java.rmi.*;
import java.rmi.registry.*;
import java.rmi.server.*;
import java.net.*;
public class RmiServer extends java.rmi.server.UnicastRemoteObject
implements ReceiveMessageInterface
{
int thisPort;
String thisAddress;
Registry registry; // rmi registry for lookup the remote objects.
// This method is called from the remote client by the RMI.
// This is the implementation of the gReceiveMessageInterfaceh.
public void receiveMessage(String x) throws RemoteException
{
System.out.println(x);
}
public RmiServer() throws RemoteException
{
try{
// get the address of this host.
thisAddress= (InetAddress.getLocalHost()).toString();
}
catch(Exception e){
throw new RemoteException("can't get inet address.");
}
thisPort=3232; // this port(registryfs port)
System.out.println("this address="+thisAddress+",port="+thisPort);
try{
// create the registry and bind the name and object.
registry = LocateRegistry.createRegistry( thisPort );
registry.rebind("rmiServer", this);
}
catch(RemoteException e){
throw e;
}
}
static public void main(String args[])
{
try{
RmiServer s=new RmiServer();
}
catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
RmiClient.java
import java.rmi.*;
import java.rmi.registry.*;
import java.net.*;
public class RmiClient
{
static public void main(String args[])
{
ReceiveMessageInterface rmiServer;
Registry registry;
String serverAddress=args[0];
String serverPort=args[1];
String text=args[2];
System.out.println("sending "+text+" to "+serverAddress+":"+serverPort);
try{
// get the �gregistry�h
registry=LocateRegistry.getRegistry(
serverAddress,
(new Integer(serverPort)).intValue()
);
// look up the remote object
rmiServer=
(ReceiveMessageInterface)(registry.lookup("rmiServer"));
// call the remote method
rmiServer.receiveMessage(text);
}
catch(RemoteException e){
e.printStackTrace();
}
catch(NotBoundException e){
e.printStackTrace();
}
}
}
ReceiveMessageInterface.java
import java.rmi.*;
public interface ReceiveMessageInterface extends Remote
{
public void receiveMessage(String x) throws RemoteException;
}
This works fine normally , but when the a computer is connected to internet through mobile or it shares internet from other pc it doesn't work
I get this error.
java.net.connectexception connection timeout
when i tried to telnet it fails to connect but when i try to run this program that pc
to my pc it works.
Please let me know how to solve this issue.
Sounds like a firewall or proxy server issue.

Kryonet Client connection issues Java

I have a kryonet client/server that work find.. well mostly. The client remains idle and eventually disconnects after awhile but thats not the issue i'm trying to solve currently. Currently, the server and client can establish a connection and send data back and forth(Before the client times out) as long as the client and server are on the same computer. If you try to connect to a different computer on the LAN the connection times out and fails.
So here's my question(s):
What would be a possible cause for the connection issue?
What is the proper way to keep a client alive? ( secondary goal but if you know it, that'd be great)
*I'm using LibGDX and Kryonet for this. As far as I know, they shouldn't have any conflicts.
Server:
package com.me.mygdxgame;
import java.io.IOException;
import java.util.ArrayList;
import com.badlogic.gdx.math.Vector2;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.Listener;
import com.esotericsoftware.kryonet.Server;
import com.me.mygdxgame.Network.Obstacles;
public class GameServer {
Server server;
public GameServer () throws IOException {
server = new Server() {
protected Connection newConnection () {
return new PlayerConnection();
}
};
Network.register(server);
//Sends Stuff to Client
server.addListener(new Listener() {
public void received (Connection c, Object object) {
PlayerConnection connection = (PlayerConnection)c;
if (object instanceof Obstacles) {
if (connection.name != null) return;
ArrayList<Vector2> obs = ((Obstacles)object).obstacles;
if (obs == null) return;
System.out.println("Obstacles recieved.");
for(int i = 0; i < obs.size(); i++)
System.out.println("Obstacle " + i + "- x: " + obs.get(i).x );
return;
}
}
});
server.bind(Network.port);
server.start();
}
public void sendAll () { //Send out data
Obstacles ob = new Obstacles();
ob.obstacles = new ArrayList<Vector2>();
for(int i =0; i < Map.obstacles.size(); i++){
ob.obstacles.add(new Vector2(Map.obstacles.get(i).x,Map.obstacles.get(i).y));
}
server.sendToAllTCP(ob);
}
static class PlayerConnection extends Connection {
public String name;
}
}
Client:
package com.me.mygdxgame;
import java.awt.EventQueue;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import com.badlogic.gdx.ApplicationListener;
import com.esotericsoftware.kryonet.Client;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.Listener;
import com.me.mygdxgame.Network.Obstacles;
public class GameClient implements ApplicationListener{
Client client;
String name;
String RefreshHost;
boolean Connected = false;
ArrayList<String> hosts = new ArrayList<String>();
public static String host;
public GameClient (String host) {
client = new Client();
client.start();
this.host = host;
Network.register(client);
client.addListener(new Listener() {
public void connected (Connection connection) {
System.out.println("connected");
Connected = true;
}
public void received (Connection connection, Object object) {
if (object instanceof Obstacles) {
Obstacles obs = (Obstacles)object;
System.out.println("Obstacle recieved on client - " + obs.obstacles.size());
client.sendTCP(obs);
System.out.println("Obstacles sent back.");
return;
}else {
System.out.println("invalid packet");
}
}
public void disconnected (Connection connection) {
EventQueue.invokeLater(new Runnable() {
public void run () {
System.out.println("closed");
Connected = false;
client.close();
}
});
}
});
new Thread("Connect") {
public void run () {
try {
client.connect(5000, GameClient.host, Network.port);
System.out.println("Connected!");
client.setKeepAliveTCP(NORM_PRIORITY);
while(Connected) {
//System.out.println(client.isIdle());
}
client.run();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}.start();
}
#Override
public void create() {
// TODO Auto-generated method stub
}
#Override
public void resize(int width, int height) {
// TODO Auto-generated method stub
}
#Override
public void render() {
// TODO Auto-generated method stub
}
#Override
public void pause() {
// TODO Auto-generated method stub
}
#Override
public void resume() {
// TODO Auto-generated method stub
}
#Override
public void dispose() {
// TODO Auto-generated method stub
}
}
I suggest you set the host BEFORE you start the client
public GameClient (String host) {
client = new Client();
this.host = host;
client.start();
I am not familiar with kryonet Client, but it makes sense to do it that way.
Generally make sure that your client is trying to connect to the host that you have server running on...
One possible cause for such connection issue is a firewall blocking your Network.port
Another one, sorry but I have to ask: Is the server-app running in the other machine?
I ask because I dont'see a main function in your server code
public static void main(String[] args) throws IOException {
Log.set(Log.LEVEL_DEBUG);
new GameServer();
}
I use to get running my server-app with this terminal command
java -jar myserverfile.jar
How do you get it running in the "remote" machine?
By the way, I am using libgdx and kryonet for my game and so far I haven't get issues using them together.
In my case I have the server in a AWS instance listening for game-client testing from my computer.

Categories