Java websocket peer-to-peer client socket management - java

I am trying to build peer-to-peer cross platform chat mobile application but I am new to server programming. The server is written in java and I am using spark micro framework for server and org.java_websocket for socket connections I saw some tutorials and have implemented a class that extends WebSocketServer and I do get how the socket will work and the interface methods will get called. But I am unable to figure out a few things:
How to manage multiple clients, and how will they connect to my server. Suppose 1000 users want to connect to my server how to implement that.
If somehow I managed to connect 1000 users then if user 23 wants to chat with user 52 how will that happen.
The code I found on the tutorial requires for me to specify a port so how will I decide which port is free from my server and no other client is connected to that port and according to my knowledge only one socket can be opened on one port so how will I make my server handle millions of users (assuming I get that many).
P.S. I am using Tomcat server
The code below is what I found in the tutorial:
public class SocketHandler extends WebSocketServer {
public SocketHandler(int port) throws UnknownHostException{
super(new InetSocketAddress( port ));
}
public SocketHandler(InetSocketAddress address) throws UnknownHostException{
super(address);
}
#Override
public void onOpen( WebSocket conn, ClientHandshake handshake ) {
this.sendToAll( "new connection: " + handshake.getResourceDescriptor() );
System.out.println( conn.getRemoteSocketAddress().getAddress().getHostAddress() + " entered the room!" );
}
#Override
public void onClose( WebSocket conn, int code, String reason, boolean remote ) {
this.sendToAll( conn + " has left the room!" );
System.out.println( conn + " has left the room!" );
}
#Override
public void onMessage( WebSocket conn, String message ) {
this.sendToAll( message );
System.out.println( conn + ": " + message );
}
#Override
public void onWebsocketMessageFragment(WebSocket conn, Framedata frame) {
super.onWebsocketMessageFragment(conn, frame);
System.out.println( "received fragment: " + frame );
}
}

Related

Connection failed with racer reasoner

I'm trying to use racer (Description Logic reasoner), but i get the following error
com.racersystems.jracer.RacerClientException: Connection refused: connect
at com.racersystems.jracer.RacerClient.openConnection(RacerClient.java:76)
at test.Test.main(Test.java:12)
the code i'm executing is the following :
package test;
import com.racersystems.jracer.*;
public class Test {
public static void main(String[] argv) {
String ip = "127.0.0.1";
int port = 8088;
String filename="\"/jracer-2-0.zip_expanded/jracer-2-0/demo/people+pets.owl\"";
RacerClient racer = new RacerClient(ip,port);
try {
racer.openConnection();
System.out.println(racer.sendRaw("(owl-read-file " + filename + ")"));
System.out.println(racer.sendRaw("(all-atomic-concepts)"));
racer.closeConnection();
}
catch (Exception e) {
e.printStackTrace();
}
}}
I don't know who to solve it ?
Any suggestions ?
You are apparently trying to connect to a service that is running on the same machine as you are running the program ... using the 127.0.0.1 loopback interface.
The fact that it is giving you a "connection refused" response means that the service is not currently running on "this machine" or the port that you have specified.
The solution will be to ensure that the service is running and listening on the specified IP and port; e.g. check the IP address and port, and start or restart the service.

Netty4: Sending multiple request to different servers

I have one client which is sending multiple requests. Each request is going to different server. So, 200 requests going to 200 different servers.
I have created one even loop group with different bootstrap for different connection.
Should i use 200 channels for 200 requests or a single channel. Below is my code, right now i am using single channel:
public HttpClientDemo(int serverPort)
{
this.serverPort = serverPort;
this.pipelineFactory = new HTTPClientInitializer();
this.workerGroup = new NioEventLoopGroup();
}
public void connect(String address, int timeout) {
connectAsync(address).syncUninterruptibly();
}
private ChannelFuture connectAsync(final String address)
{
return new Bootstrap()
.group(workerGroup)
.channel(NioSocketChannel.class)
.handler(pipelineFactory).connect(address,serverPort).addListener(new ChannelFutureListener() {
#Override
public void operationComplete(ChannelFuture future) {
if(future.isSuccess())
{
log.info("Client is able to connect to: " + address);
}
else
{
log.error("Client not able to connect to: " + address + " " + future.cause());
}
}
});
}
Each Channel is connected to a different endpoint and so different server, this means you will need different Channels.

Websocket connection closed automatically?

I'm newbie to the web-socket programming...
I have the following JavaScript client code:
var connection = new WebSocket('ws://localhost:8080/OmegaThings/registerdevice');
connection.onopen = function () {
console.log("Socket has been opened state = " + connection.readyState);
connection.send('Ping'); // Send the message 'Ping' to the server
connection.send('Websocket client');
};
console.log("Socket has been opened state = " + connection.readyState);
connection.send('finish');
// Log errors
connection.onerror = function (error) {
console.log('WebSocket Error ' + error);
};
// Log messages from the server
connection.onmessage = function (e) {
console.log('Server: ' + e.data);
};
Java endpoint:
#ServerEndpoint("/registerdevice")
public class RegisterDeviceEndPoint
{
private static final Logger LOG = Logger.getLogger(RegisterDeviceEndPoint.class.getName());
#OnOpen
public void connectionOpened()
{
LOG.log(Level.INFO, "******************connection opened**************");
}
#OnMessage
public synchronized void processMessage(Session session, String message)
{
LOG.log(Level.INFO, "received message: {0}", message);
}
#OnClose
public void connectionClosed()
{
LOG.log(Level.INFO, "connection closed");
}
}
on the firefox console I got the following output:
"Socket has been opened state = 1"
InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable
"Socket has been opened state = 0"
on the GlassFish server log I got "ping" and "Websocket client", but the connection closed after onopen event exit(not sure), thus, the last word "finish" doesn't appear on the log and the error occurs.
I want to know if my code is correct?
What causes the error? javascript code, GlassFish server configuration or the java endpoint code?
Try to change the glassfish 8080 port, eg: 8887, or make sure Your antivirus/other application are not using port 80, I previously had experience where my server websocket was blocked by antivirus which using port 80.

NoSuchObjectException - No such object in table

I'm try to set up a simple RMI implementation, but I'm having some trouble.
The server starts up fine, but the client can never seem to find the remote object (Naming.lookup fails every time). From reading around people have mentioned storing the remote object (Bank) in a static variable, but that hasn't worked either.
UPDATE: If I remove all references to the port number, the whole thing seems to work fine. Does anyone know why that is?
Server:
public class Bank extends UnicastRemoteObject implements BankInterface {
public static void main(String args[]) throws Exception {
try{
System.setSecurityManager(new SecurityManager());
System.out.println("Security Manager set.");
Bank myBank = new Bank(Integer.parseInt(args[0]));
System.out.println("Bank instance created");
Naming.rebind("Bank", myBank);
System.out.println("Name rebind completed.");
System.out.println("Server ready for requests!");
}catch(Exception e){
System.out.println("Error in main - " + e.toString());
}
}
}
Client
public class ATM {
public static void main (String args[]) throws Exception {
String URL = "//" + args[0] + ":" + args[1] + "/Bank";
System.out.println("Connecting to: " + URL);
BankInterface bank = (BankInterface)Naming.lookup(URL);
System.out.println("Connected!");
}
}
Stacktrace
Exception in thread "main" java.rmi.NoSuchObjectException: no such object in tab
le
at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(Stream
RemoteCall.java:276)
at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:
253)
at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:379)
at sun.rmi.registry.RegistryImpl_Stub.lookup(Unknown Source)
at java.rmi.Naming.lookup(Naming.java:101)
at ATM.main(ATM.java:8)
Commands I'm running from cmd.exe are:
rmiregistry
java Bank 7777
java ATM localhost 7777 testMethod
You're running the Registry on its default port, and binding to that Registry, by not using a port number in the bind string, but you're looking up a non-existent Registry on port 7777. The bind string and the lookup string should be the same.
NB lookup isn't the same as connecting. There is no connection to your remote object until you call one of its remote methods.

KryoNet: Client disconnects immediately after connecting

This seems to be a popular problem, but I'm still having trouble finding a solution even after spending a lot of time troubleshooting. I'm hoping there's an updated solution.
I'm setting up a simple Server and Client with the KryoNet Java networking library. My problem is that my client disconnects immediately after connecting to the server.
Here is my code:
Server
public class TheServer extends Listener {
static Server server;
static final int PORT = 8215;
public static void main(String[] args) throws IOException {
server = new Server();
server.start();
server.bind(PORT);
server.addListener(new TheServer());
System.out.println("server started on " + PORT);
}
public void connected(Connection c) {
System.out.println("connected: " + c.getID());
}
public void disconnected(Connection c) {
System.out.println("disconnected: " + c.getID());
}
}
Client
public class TheClient extends Listener {
static Client client;
static final String IP = "localhost";
static final int PORT = 8215;
public static void main(String[] args) throws IOException {
client = new Client();
client.start();
client.connect(5000, IP, PORT);
client.addListener(new TheClient());
//client.setKeepAliveTCP(2000);
}
}
After running TheServer and then TheClient, my console prints:
server started on 8215
connected: 1
disconnected: 1
Note that the time between the connection and disconnection is almost immediate, certainly less than the connection timeout time I set. Also note that I commented out the setKeepAliveTCP() method because while I do not think it is necessary, I inserted it to see if it would work.
After some more digging around, I found that starting the client with:
new Thread(client).start()
instead of
client.start()
fixes the problem.
"Starting with r122, client update threads were made into daemon threads, causing the child processes to close as soon as they finish initializing."

Categories