: Address already in use: JVM_Bind - java

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class serverNew {
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(3001);
Socket client = server.accept();
DataOutputStream os = new DataOutputStream(client.getOutputStream());
os.writeBytes("Hello Sockets\n"); client.close();
}
catch (IOException e) {
e.printStackTrace();
}
System.out.println("done???");
}
}
While I was running the above code ,i got following error
error given
Can I have some sort of help ???

found the error by myself with the help of Fast Snail>>>
need to change the port , it was that much easy.

Related

Java Object streams to libGDX project

i did try to test some stuff about Client/server communication in Java because i wanted to build a game with a client/server architecture.
So i read some articles and so on... it all worked till i tried to use the same classes and methods in a libGDX project client and the other as server was still the original java project.
than the fun started and i got class not found exceptions on the server side when the server where trying to read the object.
after that i tried to build client and server both as libGDX projects.
still the same error.
the serve:
package com.mygdx.game;
import java.io.IOException;
import java.net.*;
public class Server {
public static void main(String[] args) {
int port = 8800;
try {
ServerSocket serverSocket = new ServerSocket(port);
while (true) {
System.out.println("raedy");
Socket clientSocket = serverSocket.accept();
System.out.println(clientSocket+"verbunden!");
Worker worker = new Worker(clientSocket);
worker.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.mygdx.game;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
public class Worker extends Thread{
private Socket clientSocket;
public Worker(Socket clientsocket) {
this.clientSocket = clientsocket;
}
#Override
public void run() {
System.out.println("worker started");
try {
ObjectInputStream in= new ObjectInputStream(clientSocket.getInputStream());
Object obj = (Object) in.readObject();
if(obj instanceof Message) {
Message msg= (Message) in.readObject();
System.out.println("Client said: "+msg.getMessage());
}
System.out.println("input auf"+clientSocket.getLocalPort());
ObjectOutputStream out = new ObjectOutputStream(clientSocket.getOutputStream());
out.writeObject(new Message("Hello there!"));
System.out.println("output auf"+clientSocket.getPort());
} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.mygdx.game;
import java.io.Serializable;
public class Message implements Serializable{
private static final long serialVersionUID = 1L;
private String message;
public Message(String message) {
this.message = message;
}
public String getMessage(){
return message;
}
}
the client has the the same Message class and this:
package com.mygdx.game.desktop;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.mygdx.game.MyGdxGame;
public class DesktopLauncher {
public static void main (String[] arg) {
int port = 8800;
try {
System.out.println("hello there!");
Socket client = new Socket("localhost", port );
ObjectOutputStream out = new ObjectOutputStream(client.getOutputStream());
out.writeObject(new Message("ich bin der client"));
System.err.println(client.getPort());
ObjectInputStream in = new ObjectInputStream(client.getInputStream());
Message msg= (Message) in.readObject();
System.out.println("Server said: "+msg.getMessage());
System.out.println(client.getLocalPort());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
new LwjglApplication(new MyGdxGame(), config);
}
}
so my question is why does the same code work in normal java but when i build the same as a libGDX project and try the code there it doesn't work?
yes the message class is only for testing how a serializable object is transferred.
Later i want to send game commands via the object stream.
ps: you made it till the end! thank you :D
pps: the first try in java was without
Object obj = (Object) in.readObject();
if(obj instanceof Message)
I would really recommend you to use Kryonet instead of writing all the stuff from scratch yourself. It does exactly what you are trying to achieve, is mature and well tested with libGDX.

java RMI over the internet. host refuse connection

we are trying to get RMI working over the Internet. What we tried:
Port forwarding (1099-1100) on Client and Serverside.
shut down firewall in windows and router
tried it with tunngle (www.tunngle.net/)
our RMI Interface:
import java.rmi.RemoteException;
public interface RMIInterface extends java.rmi.Remote {
public void helloWorld(int i) throws RemoteException;
}
our RMI Server Implementation:
import java.net.MalformedURLException;
import java.rmi.AlreadyBoundException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class RMIServerTest extends UnicastRemoteObject implements RMIInterface {
public RMIServerTest() throws RemoteException {
}
#Override
public void helloWorld(int i) throws RemoteException {
for (int j = 0; j < i; j++) {
System.out.println("Hello World");
}
}
public static void main(String[] args) {
try {
LocateRegistry.createRegistry(Registry.REGISTRY_PORT);
}
catch (RemoteException ex) {
System.out.println(ex.getMessage());
}
try {
Naming.rebind("Server", new RMIServerTest());
} catch (MalformedURLException ex) {
System.out.println(ex.getMessage());
} catch (RemoteException ex) {
System.out.println(ex.getMessage());
}
}
}
and our Client:
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
public class RMIClient {
public static void main(String[] args) throws RemoteException, NotBoundException,MalformedURLException {
try {
RMIInterface serverObject = (RMIInterface) Naming.lookup("//externalServerAdress/Server");
serverObject.helloWorld(10);
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
We're still getting this Error:
Connection refused to host: 192.168.0.13; nested exception is:
java.net.ConnectException: Connection timed out: connect
192.168.0.13 is the local IP-adress of the Server behind his router. We connect on client with the external IP of the router. like "2.246.133.155" = externalServerAdress.
So we have a connection. We connect over the external IP adress of the server (WAN IP) and error shows, it gets the local IP-adress of the server, but still refuse connection.
thx for any hint.
Connection refused to host: 192.168.0.13
That's not an Internet address. It is a private address that only exists behind your router. You need to use your public IP address, and arrange port forwarding via your router.

client/server only reading one message?

my client/server works perfectly for one message, then no matter what's next it says it's blank.
I believe the problem resolves in here or my commands class:
package MyServer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
public class Main {
public static String line;
public static void main(String[] args){
while(true){
try {
//Creates a socket to receive commands from!
Socket socket = new Socket("localhost", 7586);
//Uses that socket to create a Reader to read the commands!
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//Waits for Lines to be sent and then executes them!
while(true){
line = in.readLine();
if(line != null){
Commands.ReceiveCommand();
}else {
break;
}
}
} catch (UnknownHostException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
or in my commands:
package MyServer;
import javax.swing.JOptionPane;
public class Commands {
static String command = (Main.line).toString(); //<--This was the problem, just had to move it into the method below.
public static void ReceiveCommand(){
if(command.equals("test")){
JOptionPane.showMessageDialog(null,"works","command: " + command,JOptionPane.WARNING_MESSAGE);
//System.out.println("WORKEDS MOFO");
command = "";
}else{
JOptionPane.showMessageDialog(null,"not recognized","command: " + command,JOptionPane.WARNING_MESSAGE);
//System.out.println("no bueno");
//System.out.println("line is " + command);
command = "";
}
}
}
Edit: For some reason when debugging, command is just blank no matter what after it's been used once, so it might be in my main server class:
package MyClient;
import java.util.List;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class Main {
//Sets the Port
final static int PORT = 7591;
//Creates a list of Connected Clients
static List<Socket> connectedClients = new ArrayList<Socket>();
public static void main(String[] args){
//Creates a Thread to Send Messages to connectedClients
new Thread(new messageThread()).start();
try {
//Creates the ServerSocket
ServerSocket serverSocket = new ServerSocket(PORT);
while(true){
//Waits for a Connection and Accepts it...
Socket clientSocket = serverSocket.accept();
System.out.println("A Client has connected!");
//Adds it to the List
connectedClients.add(clientSocket);
}
} catch (IOException e) {
e.printStackTrace();
}
} }
and the messageThread:
package MyClient;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class messageThread implements Runnable {
public void run() {
while(true){
System.out.println(">>");
Scanner in = new Scanner(System.in);
String command = in.nextLine();
for(Socket clientToSendCommand : Main.connectedClients){
try {
PrintWriter commandWriter = new PrintWriter(clientToSendCommand.getOutputStream());
commandWriter.println(command);
commandWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
This dosen't work, because th line
static String command = (Main.line).toString();
in the Commands-class is executed exactly once, when the Commands-class is first referenced.
When the second command is send, the class was already referenced, so this line is not executed again.
To solve this put the line inside the method, or - much better - pass it as a parameter to the method.
P.S.: Have you mixed up the packages? The class with the ServerSocket should be the server and thus be in the MyServer package. :-)

How to create an event in Java

I am currently working on a multi-threaded socket based Java program that should allow multiple threads to send request to this program. This should be handled with the event activation but I am having hard time understanding events and their implementation. Below is the code that should allow more than 1 thread to communicate with the program but I only have 1 thread there. Can someone please shed more light on this? Much appreciated.
//this is a a threads class
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Niti implements Runnable {
public String line;
public Socket soc;
public boolean active=true;
public Niti(Socket soc)
{
this.soc=soc;
this.line=line;
this.active=active;
}
public synchronized void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(soc.getInputStream()));
line=br.readLine();
while(line!=null && !line.equals("")){
if(!this.active)
break;
System.out.println(line);
line=br.readLine();
}
BufferedOutputStream bos = new BufferedOutputStream(soc.getOutputStream());
bos.write("Poruka iz Programa".getBytes());
}
catch (IOException ex) {
Logger.getLogger(Niti.class.getName()).log(Level.SEVERE, null, ex);
}
try {
soc.close();
} catch (IOException ex) {
Logger.getLogger(Niti.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
//and this is the main class
public class Server{
public static synchronized void main(String[] args) throws IOException, InterruptedException{
ServerSocket ss = new ServerSocket(1000);
while(true){
Socket sokit = ss.accept();
Niti n = new Niti(sokit);
while(true){
Thread t = new Thread(n);
t.start();
//Thread.sleep(4000);
//n.active=false;
System.out.println("nit broj:" + Thread.currentThread().getId());
}
}
}
}
Well, without look to Niti class (that is the client handler class as I suppose) you have a logic error here:
while(true){
Socket sokit = ss.accept();
Niti n = new Niti(sokit);
while(true){ // LOGIC ERROR!!!
Thread t = new Thread(n);
t.start();
//Thread.sleep(4000);
//n.active=false;
System.out.println("nit broj:" + Thread.currentThread().getId());
}
}
With the above code you are creating infinit Threads after pass the first time through accept method. What you have to do is to remove the second while(true), like this:
while(true){
Socket sokit = ss.accept();
Niti n = new Niti(sokit);
Thread t = new Thread(n);
t.start();
//Thread.sleep(4000);
//n.active=false;
System.out.println("nit broj:" + Thread.currentThread().getId());
}

NullPointerException in Thread's run method

I would really appreciate help with my program. It is some sort of chat server with multiple clients.
Here's the server code:
package com.server;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static int PORT;
private ServerSocket server;
private Socket socket;
public Server(int port) throws IOException {
PORT = port;
server = new ServerSocket(PORT);
System.out.println("server started");
try {
while (true) {
socket = server.accept();
try {
new ServeClient(socket);
} catch (IOException e) {
socket.close();
}
}
} finally {
server.close();
}
}
public static void main(String[] args) throws IOException {
int port = Integer.parseInt(args[0]);
Server server = new Server(port);
}
}
I start the server and then create a Client. The server receives connection socket from socket
and creates a ServeClient Thread.
Here's ServeClient code:
package com.server;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Enumeration;
import java.util.Vector;
import com.gui.WindowManager;
public class ServeClient extends Thread {
private final Socket socket;
private BufferedReader in;
private PrintWriter out;
private String msg;
public static final String ENDSTRING = "END";
public static Vector clients = new Vector();
public ServeClient(final Socket socket) throws IOException {
this.socket = socket;
System.out.println("socket " + socket);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream())), true);
start();
}
public void run() {
try {
clients.add(this);
while (true) {
msg = in.readLine();
if (msg == ENDSTRING)
break;
broadcast(msg);
}
System.out.println("closing...");
} catch (IOException e) {
System.err.println("IO EXCEPTION");
} finally {
try {
socket.close();
} catch (IOException e) {
System.err.println("SOCKET NOT CLOSED");
}
}
}
#SuppressWarnings("deprecation")
public void broadcast(String msg) {
synchronized (clients) {
Enumeration<ServeClient> e = clients.elements();
while (e.hasMoreElements()) {
ServeClient serveClient = e.nextElement();
try {
synchronized (serveClient.out) {
serveClient.out.println(msg);
}
} catch (Exception eee) {
serveClient.stop();
}
}
}
}
}
What i get is a NullPointerException when ServeClient invokes run() method
server started
socket Socket[addr=/127.0.0.1,port=51438,localport=8888]
Exception in thread "Thread-0" java.lang.NullPointerException
at com.server.ServeClient.run(ServeClient.java:33)
line 33 is the line with first "try" statement in ServeClient run() method
com.server.ServeClient.run(ServeClient.java:33)
I don't believe that it's happening at the try.
Open up an IDE, turn on debugging, and step through until you can see what's happening. That's the fastest way to figure out what you've missed.
There's an object that you're assuming is fine that is not. Find it.
Here's an example of how to do this properly:
http://www.kodejava.org/examples/216.html
Your problem is with the order in which static instance variables are initialised. Try doing something like:
...
private static Vector clients = null;
...
if (clients==null) {
clients = new Vector(); // consider putting this in a synchronized block
}
before you add the client to the vector.
Sorry for necroing such an old issue but it seemed like this problem wasn't resolved, so I'll give a bit of input from my end.
I've had a similar problem and the compiler also kept telling me that the problem was at the start() method. However, when I commented out the thread part and just ran the code on the same thread as the UI, the compiler directed me to the real source of the problem: the code inside the thread.
After making sure the code didn't give an error, I enclosed the code with the original thread code, and it stopped giving me the NullPointerException error.
Hope this helps someone along the way.
Remove the duplicate class declaration in JPanel.
I was trying to run a timer thread that updated a clock in the main application window.
I had created the JFrame with Eclipse/WindowBuilder and had followed a tutorial on how to make a timer. I had copied the declaration of the textfield into the class declaration to make it available for the entire class, but forgot to remove the Class Id in front of the widget definition. So it still initialized the local instance and not the global one. Thus when I accessed the global one it was still null.

Categories

Resources