ServerSocket doesn't appear in Netstat? - java

Very confused, I just posted this question but deleted it because I made many mistakes. Alright well here goes again! I have a server program in java below. When I run it I expect to see some sort of presence in netstat, but I see nothing. Here are some screen shots:
Before running server: https://www.dropbox.com/s/upo9ndbzuxbk9j1/Screenshot%202014-12-24%2002.25.49.png?dl=0
After running server (server running in top right terminal, bottom right is client and obviously left is netstat): https://www.dropbox.com/s/05urjvz3lskvzkc/Screenshot%202014-12-24%2002.28.24.png?dl=0
Somewhat long but here is the server (I run it with 63400):
import java.net.*;
import java.io.*;
public class JavaTest2 {
public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.err.println("Usage: java KnockKnockServer <port number>");
System.exit(1);
}
int portNumber = Integer.parseInt(args[0]);
try (
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
) {
String inputLine, outputLine;
// Initiate conversation with client
KnockKnockProtocol kkp = new KnockKnockProtocol();
outputLine = kkp.processInput(null);
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
outputLine = kkp.processInput(inputLine);
out.println(outputLine);
if (outputLine.equals("Bye."))
break;
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
}
}
class KnockKnockProtocol {
private static final int WAITING = 0;
private static final int SENTKNOCKKNOCK = 1;
private static final int SENTCLUE = 2;
private static final int ANOTHER = 3;
private static final int NUMJOKES = 5;
private int state = WAITING;
private int currentJoke = 0;
private String[] clues = { "Turnip", "Little Old Lady", "Atch", "Who", "Who" };
private String[] answers = { "Turnip the heat, it's cold in here!",
"I didn't know you could yodel!",
"Bless you!",
"Is there an owl in here?",
"Is there an echo in here?" };
public String processInput(String theInput) {
String theOutput = null;
if (state == WAITING) {
theOutput = "Knock! Knock!";
state = SENTKNOCKKNOCK;
} else if (state == SENTKNOCKKNOCK) {
if (theInput.equalsIgnoreCase("Who's there?")) {
theOutput = clues[currentJoke];
state = SENTCLUE;
} else {
theOutput = "You're supposed to say \"Who's there?\"! " +
"Try again. Knock! Knock!";
}
} else if (state == SENTCLUE) {
if (theInput.equalsIgnoreCase(clues[currentJoke] + " who?")) {
theOutput = answers[currentJoke] + " Want another? (y/n)";
state = ANOTHER;
} else {
theOutput = "You're supposed to say \"" +
clues[currentJoke] +
" who?\"" +
"! Try again. Knock! Knock!";
state = SENTKNOCKKNOCK;
}
} else if (state == ANOTHER) {
if (theInput.equalsIgnoreCase("y")) {
theOutput = "Knock! Knock!";
if (currentJoke == (NUMJOKES - 1))
currentJoke = 0;
else
currentJoke++;
state = SENTKNOCKKNOCK;
} else {
theOutput = "Bye.";
state = WAITING;
}
}
return theOutput;
}
}
Now when I run the client I can see the presence in netstat at the very top, the two sockets as my server and client running on same computer. But still no server socket :(
Screenshot: https://www.dropbox.com/s/bnrbyk41mjob5bg/Screenshot%202014-12-24%2002.25.53.png?dl=0
Code for client (ran with 127.0.0.1 64300):
import java.io.*;
import java.net.*;
public class JavaTest {
public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.err.println(
"Usage: java KnockKnockClient <host name> <port number>");
System.exit(1);
}
String hostName = args[0];
int portNumber = Integer.parseInt(args[1]);
try (
Socket kkSocket = new Socket(hostName, portNumber);
PrintWriter out = new PrintWriter(kkSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(kkSocket.getInputStream()));
) {
BufferedReader stdIn =
new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser;
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("Bye."))
break;
fromUser = stdIn.readLine();
if (fromUser != null) {
System.out.println("Client: " + fromUser);
out.println(fromUser);
}
}
} 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);
}
}
}
Thanks in advance to anyone who takes the time to figure it out!
I think it may just be netstat but I still want to know why as when I run lsof -i :64300
it shows my java process, when only the server is running. And when I run that with everything I see 3 (as you can see in the left terminal in this screenshot https://www.dropbox.com/s/1focc9dmhkidtan/Screenshot%202014-12-24%2002.52.22.png?dl=0). I cancel the netstat after it shows me what I "think" is relevant because I cannot interpret the rest. I dont know if its there. Hopefully someone helps!
Ok I am just finding out more as I write this cause I cannot post for 90 minutes but, now when I use intellij idea and run it there. Just the server, there is no change, but when I add the client I see everything!
before anything: https://www.dropbox.com/s/akupewmprcld0b3/Screenshot%202014-12-24%2002.59.05.png?dl=0
server: https://www.dropbox.com/s/uvxmz0jvjozbkyy/Screenshot%202014-12-24%2002.59.34.png?dl=0
client + server: https://www.dropbox.com/s/bssa16s1n3adwdq/Screenshot%202014-12-24%2003.00.00.png?dl=0
What is going on.... I also see 6 localhosts instead of 3... God this is interesting or I am just making one very silly mistake. But I am starting to doubt any of this matters.

netstat omits listening sockets by default. There's an -l option or -all for all sockets. – laune

Related

Java TCP byteArray transfering using buffer and threading

So basically what I want to do is: Create a very simple multithreaded TCP server that can connect to several clients at once. This using threads and transferring messages through Byte[] and returning an echo of the message.
I have never touched anything related to server programming or TCP before, so I expect to have made a lot of mistakes. I am open for improvement and suggestions.
I made a simple Server class:
public class TCPEchoServer {
public static final int SERVERPORT = 4950;
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(SERVERPORT);
while (true) {
Socket clientSocket = serverSocket.accept();
Runnable connectionHandler = new TCPConnectionHandler(clientSocket);
new Thread(connectionHandler).start();
}
}
}
And the connection handler class:
public class TCPConnectionHandler implements Runnable {
private final Socket clientSocket;
private int msgLength = 0;
private byte[] data;
public TCPConnectionHandler(Socket clientSocket) {
this.clientSocket = clientSocket;
}
#Override
public void run() {
try {
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(clientSocket.getOutputStream());
InputStream in = clientSocket.getInputStream();
DataInputStream dis = new DataInputStream(in);
msgLength = dis.readInt();
data = new byte[msgLength];
if (msgLength > 0) {
dis.readFully(data);
}
String message = inFromClient.readLine();
System.out.println("Message recieved: " + message);
outToClient.writeBytes(String.valueOf(data));
clientSocket.close();
}
catch (IOException e) {
System.out.printf("Could not listen on port: " + clientSocket.getLocalPort());
}
}
}
And the Client class:
public class TCPEchoClient {
public static final int MYPORT = 0;
public static int BUFFSIZE = 0;
public static Socket socket;
public static final String MSG = "An Echo Message! LOL";
public static String RETURNMSG = "";
public static final byte[] messageByteArr = MSG.getBytes(Charset.forName("UTF-8"));
private static final Pattern PATTERN = Pattern.compile(
"^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");
public static void main(String[] args) throws IOException, InterruptedException {
if (args.length != 4) {
System.err.printf("ERROR: The EchoClient expects 4 parameter inputs:");
System.out.printf("IP address, Port number, message rate (msg/second).");
System.exit(1);
}
if (!isValidIP(args[0])) {
System.out.printf("ERROR: The entered IP address is not a valid IPv4 address.");
System.out.printf("Please enter a valid IPv4 address as the first argument.");
System.exit(1);
}
if (Integer.parseInt(args[1]) < 0 || Integer.parseInt(args[1]) > 65535) { //If the portnumber is negative or bigger than the highest portnumber (unsigned 16-bit integer)
System.out.printf("ERROR: The chosen portnumber is outside the available range.");
System.out.printf("Expected portnumbers: 0-65535");
System.exit(1);
}
if (Integer.parseInt(args[3]) < messageByteArr.length) {
System.out.println("Buffer size can not be smaller than the message size.");
System.out.println("Current message size: " + messageByteArr.length);
System.exit(1);
}
BUFFSIZE = Integer.parseInt(args[3]);
byte[] buf = new byte[BUFFSIZE];
DataOutputStream outToServer = null;
BufferedReader serverEcho = null;
try {
socket = new Socket(args[0], Integer.parseInt(args[1]));
outToServer = new DataOutputStream(socket.getOutputStream());
serverEcho = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
System.out.println("Unknown host address: " + args[0]);
System.exit(1);
} catch (IOException e) {
System.out.println("Could not access port " + Integer.parseInt(args[1]));
System.exit(1);
}
int msgLength = 0;
int msgStart = 0;
if (msgLength < 0) {
throw new IllegalArgumentException("Negative length not allowed.");
}
if (msgStart < 0 || msgStart >= messageByteArr.length) {
throw new IndexOutOfBoundsException("Out of bounds: " + msgStart);
}
for (int i = 1; i <= Integer.parseInt(args[2]); i++) {
outToServer.writeInt(msgLength);
if (msgLength > 0) {
outToServer.write(messageByteArr, msgStart, msgLength);
System.out.println("Message sent: " + MSG);
}
RETURNMSG = serverEcho.readLine();
System.out.println("ECHO MESSAGE: " + RETURNMSG);
}
socket.close();
}
private static boolean isValidIP(final String ip) {
return PATTERN.matcher(ip).matches();
}
}
I ran into a problem just now as well, the print outs worked before on the client and sever, but now when a message is sent. Nothing happens at all.
My main question is how I can incorporate a buffer and use it when sending and receiving messages.
You have a loop in the client that will wait args[2] times the RETURNMSG, the server will send this message only once. The RETURNMSG reading code should be outside (after) the for loop.
You should flush the buffer once you've finished writing in it.
This should be done in both client and server, since your client will wait the RETURNMSG forever depending how your protocol will evolve in the future.

Reading data from a socket java

So, I'm trying to read data from a socket. I have established a connection and sent a message to the other socket which is listening for such, but it doesn't seem to recieve anything.
Client code:
import java.net.*;
import java.io.*;
import java.util.*;
public class TCPClient {
/*Conecting to server.
*/
public static void Client(String[] args){
int port = 47361;
Scanner in = new Scanner(System.in);
System.err.print("Starting up...");
Socket CS1 = null; //Declaring CS1 as a socket
DataOutputStream DOS1 = null; //Declaring an outputput data stream "DOS1"
DataInputStream DIS1 = null; //Setting the values to null
System.err.println("All created.");
System.out.println("---------");
System.out.println(" OPTIONS");
System.out.println("---------");
System.out.println("0. Connect.");
System.out.println("1. Change port.");
System.out.println("2. Cancel start-up.");
System.out.println("");
System.out.println("Choose an option.");
try {
short ans = in.nextShort();
if (ans == 2){
System.err.println("System.exit(0)");
System.exit(0);
}
if (ans == 1){
System.out.print("Enter the new port: ");
port = in.nextInt();
ans = 0;
}
if (ans == 0){
System.out.print("Enter the IP: ");
CS1 = new Socket(in.next(), port); //Creating an instane of the "CS1" socket
System.err.print("Request sent on port " + port + ".");
DOS1 = new DataOutputStream(CS1.getOutputStream());
DIS1 = new DataInputStream(CS1.getInputStream()); //creating output and input streams
System.err.println("Instances created!");
if (DIS1 != null){
System.err.println("DIS1 is connected!");
}
else {
System.err.println("DIS1 is null!");
}
if (DOS1 != null) {
System.err.println("DOS1 is connected!");
System.out.print("Enter input: ");
String FirstMessage = in.nextLine();
DOS1.writeBytes(FirstMessage);
String SecondMessage = DIS1.readLine();
System.out.println(SecondMessage);
if (SecondMessage.equals(FirstMessage)) {
}
else {
System.out.println("Please check the code, FirstMessage != SecondMessage");
}
}
else {
System.err.println("DOS1 is null!");
}
if (CS1 != null) {
System.err.println("CS1 is connected!");
}
else {
System.err.println("CS1 is null!");
}
DIS1.close();
DOS1.close();
CS1.close(); //closing everything
}
}
catch (IOException e){
System.err.println("IOException: " + e.getMessage());
}
}
}
Server code:
import java.net.*;
import java.io.*;
import java.util.*;
public class TCPServer {
/*Connecting to client
*/
public static void Server (String[] args) {
System.err.print("Starting up...");
ServerSocket SS1 = null;
DataOutputStream DOS1 = null;
DataInputStream DIS1 = null;//Setting the values to null
System.err.println("All created.");
Scanner in = new Scanner(System.in);
try {
SS1 = new ServerSocket(47361); //setting the socket SS1 to port 5000 and creating an instance
System.err.print("Listening on port 47361...");
Socket CS1 = SS1.accept(); //accepting the connection request
DOS1 = new DataOutputStream(CS1.getOutputStream());
DIS1 = new DataInputStream(CS1.getInputStream());//creating output and input streams
System.err.println("Instances created!");
if (DIS1 != null){
System.err.println("DIS1 is connected!");
System.err.println(DIS1);
}
else {
System.err.println("DIS1 is null!");
}
if (DOS1 != null) {
System.err.println("DOS1 is connected!");
System.err.println(DOS1);
}
else {
System.err.println("DOS1 is null!");
}
if (SS1 != null) {
System.err.println("SS1 is connected!");
System.err.println(SS1);
}
else {
System.err.println("SS1 is null!");
}
String FirstMessage = null;
FirstMessage = DIS1.readLine();
System.out.println(FirstMessage);
String SecondMessage = FirstMessage;
DOS1.writeBytes(SecondMessage);
DIS1.close();
DOS1.close();
SS1.close(); //closing everything
}
catch (IOException error){
System.err.println("IOException " + error.getMessage());
}
catch (java.util.InputMismatchException error2){
System.err.println("IOException " + error2.getMessage());
}
}
}
It's pretty much an EchoServer so far, without Buffered. I looked in the debugger and it gets stuck on the FirstMessage = DIS1.readLine(); line in the server and the String SecondMessage = DIS1.readLine(); in the client. Also, both the server and client are waiting for input even after I've entered any possible input. Why is this happenenig? And how can I make this work?
A side note: I know that an i/o stream or a socket will not, ever, equal null. Also, the compiler is warning me that the class java.io.DataInputStream has been deprecated. What other classes do you recommend using?
Another side note: I am new to IO, please don't kill me about it haha :)
Thanks!
Usual problem. You're reading lines but you're not writing lines. Add a line terminator to the message when writing.

Cannot send commands via Sockets

I'm new to the world of Java and now I'm trying to create a socket program. I created a server and a client, but they didn't seem to work. Now I post the code.
This is the server:
import java.net.*;
import java.io.*;
public class TCPCmdServer
{
public int port;
public ServerSocket server;
TCPCmdServer (int port)
{
this.port = port;
if(!createServer())
System.out.println("Cannot start the server");
else System.out.println("Server running on port " + port);
}
public boolean createServer ()
{
try
{
server = new ServerSocket(port);
}
catch (IOException e)
{
e.printStackTrace();
return false;
}
return true;
}
public static void main (String [] args)
{
TCPCmdServer tcp = new TCPCmdServer(5000);
boolean flag = true;
while (flag)
{
try
{
Socket socket = tcp.server.accept();
System.out.println("A client has connected");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
out.write("Welcome on the server... type the commands you like, type END to close me\n");
out.flush();
String cmd = in.readLine();
System.out.println("Recieved: " + cmd);
if (cmd.equals("END"))
{
System.out.println("Shutting down server...");
socket.close();
in.close();
out.close();
flag = false;
}
else
{
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader pRead = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = pRead.readLine()) != null)
{
System.out.println(line);
out.write(line + "\n");
out.flush();
}
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
}
And this is the client:
import java.net.*;
import java.io.*;
public class TCPCmdClient
{
public Socket socket;
public int port;
public String ip;
TCPCmdClient (String ip, int port)
{
this.ip = ip;
this.port = port;
if (!createSocket())
System.out.println("Cannot connect to the server. IP: " + ip + " PORT: " + port);
else System.out.println("Connected to " + ip + ":" + port);
}
public boolean createSocket ()
{
try
{
socket = new Socket(ip, port);
}
catch (IOException e)
{
e.printStackTrace();
return false;
}
return true;
}
public static void main (String [] args)
{
TCPCmdClient client = new TCPCmdClient("127.0.0.1", 5000);
try
{
BufferedReader sysRead = new BufferedReader(new InputStreamReader(System.in));
BufferedReader in = new BufferedReader(new InputStreamReader(client.socket.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.socket.getOutputStream()));
String response = in.readLine();
System.out.println("Server: " + response);
boolean flag = true;
while (flag)
{
System.out.println("Type a command... type END to close the server");
String cmd = sysRead.readLine();
out.write(cmd + "\n");
out.flush();
if (cmd.equals("END"))
{
client.socket.close();
sysRead.close();
in.close();
out.close();
flag = false;
} else
{
String outputline;
while ((outputline = in.readLine()) != null)
System.out.println(outputline);
}
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
[old]
I believe the problem is with the input and output streams, but I can't understand why they don't work.
The expected behavior is as follows: The client connects to the server then the server send response. The client asks the user to insert a MS-DOS command (or a "END" command), the command is then sent to the server. The server executes the command on the computer where it is running (in case the command is END it closes the connection). Then the server sends the result of the command to the client, and the client displays it to the user.
[/old]
Now the only problem is that I have to close and re-open a client any time I like to execute a new command
In your server code, you are creating a new socket for every command you received from the client. That is why you have to open a new client every time you want to send a command to the server. To correct this, first you need to remove the while(flag) loop in server code. Then you can use the following to establish the connection to the client and send and receive command and output between them.
Socket socket = tcp.server.accept();
System.out.println("A client has connected");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
out.write("Welcome on the server... type the commands you like, type END to close me\n");
out.flush();
try {
while(!(cmd = in.readLine()).equals("END")) {
System.out.println("Recieved: " + cmd);
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader pRead = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = pRead.readLine()) != null) {
System.out.println(line);
out.write(line + "\n");
out.flush();
}
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
System.out.println("Shutting down server...");
socket.close();
in.close();
out.close();
}
In TCPCmdServer.java, try changing
out.write("Welcome on the server... type the commands you like, type END to close me");
to
out.write("Welcome on the server... type the commands you like, type END to close me\n");
out.flush();
Also, change
out.write(buffer.toString());
to
out.write(buffer.toString() + "\n");
out.flush();
In TCPCmdClient.java
change
out.write(cmd);
to
out.write(cmd + "\n");
out.flush();
response = in.readLine();
System.out.println("Server: " + response);

Why is this basic client-server program not passing data?

I am following the Java Trail on networking. The three KnockKnock classes used as examples (client, server, and protocol) work as intended when I copy/paste them into Eclipse. However, what I really want to do is eliminate the protocol class and just have the server echo back to the client whatever I type into the console. I tried modifying the server program mainly by commenting out references to the protocol class, but somehow, I ended up breaking the program.
I am so new that I am clueless as to what is wrong and the more I search for an answer in ebooks and on websites the more confused I get. All I have discovered is that I know next to nothing about how IO streams really work. I pasted all three classes below in the order: server, client, protocol. Where is the problem and why is it a problem:
Server:
import java.net.*;
import java.io.*;
public class KnockKnockServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
System.out.println("Client Accepted");
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
String inputLine, outputLine;
//KnockKnockProtocol kkp = new KnockKnockProtocol();
//outputLine = kkp.processInput(null);
//out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
//outputLine = kkp.processInput(inputLine);
//out.println(outputLine);
out.println(inputLine);
if (inputLine.equals("Bye."))
break;
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
Client:
import java.io.*;
import java.net.*;
public class KnockKnockClient {
public static void main(String[] args) throws IOException {
Socket kkSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
kkSocket = new Socket("localhost", 4444);
out = new PrintWriter(kkSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: taranis.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: taranis.");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser;
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("Bye."))
break;
fromUser = stdIn.readLine();
if (fromUser != null) {
System.out.println("Client: " + fromUser);
out.println(fromUser);
}
}
out.close();
in.close();
stdIn.close();
kkSocket.close();
}
}
Protocol:
import java.net.*;
import java.io.*;
public class KnockKnockProtocol {
private static final int WAITING = 0;
private static final int SENTKNOCKKNOCK = 1;
private static final int SENTCLUE = 2;
private static final int ANOTHER = 3;
private static final int NUMJOKES = 5;
private int state = WAITING;
private int currentJoke = 0;
private String[] clues = { "Turnip", "Little Old Lady", "Atch", "Who", "Who" };
private String[] answers = { "Turnip the heat, it's cold in here!",
"I didn't know you could yodel!",
"Bless you!",
"Is there an owl in here?",
"Is there an echo in here?" };
public String processInput(String theInput) {
String theOutput = null;
if (state == WAITING) {
theOutput = "Knock! Knock!";
state = SENTKNOCKKNOCK;
} else if (state == SENTKNOCKKNOCK) {
if (theInput.equalsIgnoreCase("Who's there?")) {
theOutput = clues[currentJoke];
state = SENTCLUE;
} else {
theOutput = "You're supposed to say \"Who's there?\"! " +
"Try again. Knock! Knock!";
}
} else if (state == SENTCLUE) {
if (theInput.equalsIgnoreCase(clues[currentJoke] + " who?")) {
theOutput = answers[currentJoke] + " Want another? (y/n)";
state = ANOTHER;
} else {
theOutput = "You're supposed to say \"" +
clues[currentJoke] +
" who?\"" +
"! Try again. Knock! Knock!";
state = SENTKNOCKKNOCK;
}
} else if (state == ANOTHER) {
if (theInput.equalsIgnoreCase("y")) {
theOutput = "Knock! Knock!";
if (currentJoke == (NUMJOKES - 1))
currentJoke = 0;
else
currentJoke++;
state = SENTKNOCKKNOCK;
} else {
theOutput = "Bye.";
state = WAITING;
}
}
return theOutput;
}
}
I think your problem is just both apps are waiting:
when KKServer starts, it waits for a client, and then it's waiting until the client "says" something, and the client is waiting until the server says something before waiting for the user input

Java Server Guessing Game - Multiple Client Issue

This is an Issue I am having with my guessing game. Essentially what I want to do is have a server and have many clients connect to it. Currently that is done I am able to connect clients to the server to play a game, a number guessing game. The problem is I want each individual client to be able to play the game. Currently the game is being played on the server itself. So although multiple clients can join, the game starts again each time a client joins. When the correct answer is inputed the server gives the client his score. Just to be clear I am running the server class then I am running the client class. I want to be able to play the game on the client class window not the server window. Here is my code can you please advise me on what to do. The guessing game is derived from the java sun knock knock tutorial. Found here http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html
Thanks.
Client Class
import java.io.*;
import java.net.*;
public class GClient {
public static void main(String[] args) throws IOException {
Socket kkSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
kkSocket = new Socket("127.0.0.1", 4444);
out = new PrintWriter(kkSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: taranis.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: taranis.");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser;
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("Bye."))
break;
fromUser = stdIn.readLine();
if (fromUser != null) {
System.out.println("Client: " + fromUser);
out.println(fromUser);
}
}
out.close();
in.close();
stdIn.close();
kkSocket.close();
}
}
Server Class
import java.net.*;
import java.io.*;
public class GServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
boolean listening = true;
try {
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(-1);
}
System.err.println("Started KK server listening on port 4040");
while (listening)
new GThread(serverSocket.accept()).start();
serverSocket.close();
}
}
Protocol Class
import java.util.*;
public class GProtocol {
int guess = 0, number = new Random().nextInt(100) + 1;
int score = 10;
int guessmade = 0;
boolean gameRunning = true;
Scanner scan = new Scanner(System.in);
public String processInput(String theInput) {
String theOutput = null;
String ID;
System.out.println("Please Enter your ID...");
ID = scan.next( );
System.out.println("Please guess the number between 1 and 100. You have 10 guesses. Your score is however many guesses you have left");
while (guess != number)
{
try {
if ((guess = Integer.parseInt(scan.nextLine())) != number) {
System.out.println(guess < number ? "Higher..." : "Lower...");
score = score - 1; // here the score variable has one value taken away form it each time the user misses a guess
guessmade = +1; // here the guess made variable is given +1 variable
}
else {
System.out.println("Correct!");
}
}
catch (NumberFormatException e) {
System.out.println("Please enter valid numbers! '");
}
}
theOutput = ID + " your score is " + score ; // here the score is returned
return theOutput;}}
Thread class
import java.net.*;
import java.io.*;
public class GThread extends Thread {
private Socket socket = null;
public GThread(Socket socket) {
super("GMultiServerThread");
this.socket = socket;
}
public void run() {
try {
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
String inputLine, outputLine;
GProtocol kkp = new GProtocol();
outputLine = kkp.processInput(null);
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
outputLine = kkp.processInput(inputLine);
out.println(outputLine);
if (outputLine.equals("Bye"))
break;
}
out.close();
in.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In Protocol class, you write Messages to System.out. The instance of the Protocol class is executed in the environment of the server, thus the output is printed to the server's output. To show the output in the client's console, you'll have to send the messages via the socket to the client and print it there.
First and foremost, the preferred thing to do is to implement Runnable instead of extend Thread. That doesn't necessarily fix your problem tho.
Now, the thing that's confusing is what you're actually trying to achieve. You said you want multiple clients to play the game, but right now each client that connects to the server starts a new game. I would assume that's the right way to do it, but you seem to want to have a single game instance and multiple clients simultaneously playing on it. That's very counter-intuitive, however you can achieve it if you simply create a single instance of the GProtocol class, pass it to multiple clients and use the synchronize keyword to ensure thread safe access to its data.

Categories

Resources