I'm trying to write a java message switch application by using a multi-threaded server and two clients. However I'm stuck at one point as error occurs when I try to run my programmes. Here are my codes for the server:
public class EchoServer extends Thread {
private static ServerSocket serverSocket;
private static Socket connection1;
private static Socket connection2;
private BufferedReader input;
private PrintWriter output;
final static int portNumber = 4434;
public EchoServer(Socket in,Socket out) throws IOException{
connection1 = serverSocket.accept();
connection2 = serverSocket.accept();
input = new BufferedReader(new InputStreamReader(in.getInputStream()));
output = new PrintWriter(out.getOutputStream(),true);
}
public void run()
{
String inputLine;
while((inputLine=input.readLine())!=null){
if(inputLine.equalsIgnoreCase("quit"))
break;
System.out.println("received:" + inputLine);
output.println(inputLine);
}
System.out.println("received quit,exiting");
}
public static void main(String args[]){
serverSocket = new ServerSocket(portNumber);
System.out.println("listening on port:"+ portNumber);
EchoServer echoserver1 = new EchoServer(connection1,connection2);
EchoServer echoserver2 = new EchoServer(connection2,connection1);
echoserver1.start();
echoserver2.start();
}
}
I also wrote two classes for client. When I run the server and then the first client, they work as expected. However when I try to run the second client, a NullPointerException is thrown, regarding to the following two lines:
input = new BufferedReader(new InputStreamReader(in.getInputStream()));
EchoServer echoserver1 = new EchoServer(connection1,connection2);
I know it's a rather long piece of codes to look at, but I'm really stuck as I can't see the problem here. The earlier single threaded version of server I wrote worked without error, so I know there's something to do about the multithreaded. Any help and advice is really appreciated. Thanks!
connection1 and connection2 are never initialized in your main method, hence you get a NullPointerException when you call in.getInputStream() in your constructor.
Not completely sure what you're trying to achieve, but looks like you might want to move these two lines
connection1 = serverSocket.accept();
connection2 = serverSocket.accept();
to your main method.
Related
I am Running into a java.net.BindException: Address already in use (Bind failed) on a server-client socket app
I am trying to learn about Java sockets using a Youtube tutorial as a reference. My code seems to match everything in the video (except variables names) but, when trying to run the server and then the client sockets, I get:
Exception in thread "main" java.net.BindException: Address already in use (Bind failed)
I have tried even printing out the local port just to make sure I connect to the right available port but, nothing works. Is there any documentation I can look into to solve this problem? or any guidance?
Server.java
public class serverSocket {
public static void main(String args[]) throws IOException{
String message, serverResponse;
ServerSocket serverSocket = new ServerSocket(56789);
System.out.print(serverSocket.getLocalPort());
Socket acceptClientRequestSocket = serverSocket.accept();
Scanner serverScanner = new Scanner(acceptClientRequestSocket.getInputStream());
message = serverScanner.next();
System.out.println(message);
serverResponse = message.toUpperCase();
PrintStream newMessage = new PrintStream(acceptClientRequestSocket.getOutputStream());
newMessage.println(serverResponse);
}
}
Client.java
public class clientSocket {
public static void main(String args[]) throws UnknownHostException, IOException {
String message,outputMessage;
Scanner clientInput = new Scanner(System.in);
Socket clientSocket = new Socket("localhost",56789);
Scanner incomingStream = new Scanner(clientSocket.getInputStream());
System.out.println("Enter a message");
message = clientInput.next();
PrintStream printClientStream= new PrintStream(clientSocket.getOutputStream());
printClientStream.println(message);
outputMessage = incomingStream.next();
System.out.println(outputMessage);
}
}
Is there any documentation I can look into to solve this problem? or any guidance?
You have probably your previously exectued program still running. Check the running java processes. Kill the the previous one and try again.
If this wouldn't help try restarting your machine. If the problem persists after that then some service is already running on this port and is starting with the OS. In that case you can either change the port number in your app or disable that service.
Im working on building my own GUI program that talks to my pc from a tablet. I have the server side done in java but my problem is on the client side.
I want to send data out the PrintWriter to the server from a separate method.
I have accomplished sending in the code below (it sends 'a') but i cant figure out how to send it from a separate method. i believe its a basic java scope problem that im not understanding. i would really appreciate the help.
I have tried moving the variables into other scopes.
import java.io.*;
import java.net.*;
public class TestClient {
public static void main(String[] args) {
String hostName = "192.168.0.3";
int portNumber = 6666;
try ( //Connect to server on chosen port.
Socket connectedSocket = new Socket(hostName, portNumber);
//Create a printWriter so send data to server.
PrintWriter dataOut = new PrintWriter(connectedSocket.getOutputStream(), true);
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))
) {
//Send data to server.
dataOut.println("a");
}catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
hostName);
System.exit(1);
}
}
public static void sendToServer() {
//I want to control the print writer from this method.
//I have failed i all the ways i have tried.
}
}
You could move the Printer-Code (try try block) into the sendToServer-method and call it via
TestClient client = new TestClient();
client.sendToServer("this is a test");
Of course the sendToServer method needs to accept a parameter then. Even better would probably be to put the main method into a Starter class and decouple it from the Client-Class that you use for sending the data.
I have created a very very basic java server with tutorials. The goal is to let gamemaker studio 2 clients connect and communicate with that server. I have more experience with GML.
So the server is starting(java) up and the client(GMS2) is connecting succesfully. I have buildin some checks to make sure. If the client send a message to the server, the server never gets it, until the clients disconnect.
this is the java code:
import java.net.*;
import java.io.*;
public class GameServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(6666);
Socket client = serverSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
out.println("hello gamemaker studio: "); //the clients receive this message
while(true) {
System.out.println("in while loop");//the server console prints this message
String string = in.readLine();//keeps stuck on this
//after client disconnect, all messages the client has sent are displayed in the console
System.out.println("reading string:" + string);
if (string == null) { break; }
out.println("we have received this answer: " + string );
System.out.println("stopped");
}
}
}
For some reason i don't know it is keeps stuck on this line:
String string = in.readLine();
I crafted a java client to test it. Everything works fine with a java client.
So there has to be something wrong with the gamemaker code
I have a server client that sends and receives info from the server socket using a PrintWriter for outgoing messages and a BufferedReader for incoming messages. I'm trying to test the client without a server connection in JUnit by sending strings to the client through the BufferedReader and reading the returned output from the PrintWriter.
class Client{
private BufferedReader incomingMessage;
private PrintWriter outgoingMessage;
private StringWriter output;
//Constructor for testing without server connection
public Client(){
output = new StringWriter();
outgoingMessage = new PrintWriter(output);
incomingMessage = new BufferedReader(new InputStreamReader(System.in));
}
//Methods for processing incoming messages and sending responses are
//omitted
//responses are sent using outgoingMessage.println("msg");
public void sendStringToInputStream(String msg){
incomingMessage = new BufferedReader(new StringReader(msg));
}
public String getOutputAsString(){
return output.toString();
}
}
This is the test I'm running.
public class ServerMessageTest {
private Client testClient;
private String output;
#Before
public void setUp(){
testClient = new Client();
}
#Test
public void testClientOutputMessage(){
testClient.sendStringToInputStream("GAME A OVER SEND OUTCOME");
output = testClient.getOutputAsString();
String testString = "GAME A OVER PLAYER 1 0 PLAYER 2 0";
Assert.assertEquals(testString, output.toString());
}
}
The test fails showing this:
org.junit.ComparisonFailure:
Expected :GAME A OVER PLAYER 1 0 PLAYER 2 0
Actual :
So there's an issue with reading the output message or setting the input message. I'm kinda new to IO stuff, so if someone could point out what I'm doing wrong I would greatly appreciate it!
Your variable names are bizarre. A BufferedReader isn't a message, and neither is a PrintWriter.
You aren't doing any output or input in this code. You need to call println() to send the message, and readLine() to receive it. Converting the reader and writer to strings accomplishes exactly nothing.
You need to create your reader and writer once per socket, not once per message.
I have a server-client pair and I want to create a listener on the client end for new server responses. I am not sure how to do this, right now I can only interact in a direct synchronous way.
Here is the server:
public class TestServer {
public static void main(String[] args) throws Exception {
TestServer myServer = new TestServer();
myServer.run();
}
private void run() throws Exception {
ServerSocket mySS = new ServerSocket(4443);
while(true) {
Socket SS_accept = mySS.accept();
BufferedReader myBR = new BufferedReader(new InputStreamReader(SS_accept.getInputStream()));
String temp = myBR.readLine();
System.out.println(temp);
if (temp!=null) {
PrintStream serverPS = new PrintStream(SS_accept.getOutputStream());
serverPS.println("Response received: " + temp);
}
}
}
}
As you can see, it sends a response when it gets one. However in general I won't be sure when other servers I use send responses, so I would like to create an asynchronous listener (or at least poll the server for a response every half-second or so).
Here is what I'm trying on the client end:
protected static String getServerResponse() throws IOException {
String temp;
try {
BufferedReader clientBR = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
temp = clientBR.readLine();
} catch (Exception e) {
temp = e.toString();
}
return temp;
}
And just for reference, yes, sending over data from client to server works fine (it System.out's the data correctly). However, when I call the above function to try and retrieve the server response, it just hangs my application, which is an Android application in case that's relevant.
What I want from a function is just the ability to ask the server if it has data for me and get it, and if not, then don't crash my damn app.
On the client side create a ConnectionManager class which will handle all the socket I/O. The ConnectionManager's connect() method will create and start a new thread which will listen for server responses. As soon as it will receive a response it will notify all the ConnectionManager's registered listeners. So in order to receive asynchronously the server responses you will have to register a listener in ConnectionManager using its register(SomeListener) method.
Also, you can have a look at JBoss Netty which is an asynchronous event-driven network application framework. It greatly simplifies and streamlines network programming such as TCP and UDP socket server.