Will immediately add null even if I'm not typing - java

I can't resolve my problem on "server has added null."
It doesn't go to the menu first to process data.
This is also similar to writing client to server question.
Here's my codes:
Student:
import java.lang.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class Student {
public static void main(String args[]) {
PrintWriter out = null;
Scanner sc = new Scanner (System.in);
//initialization
String student = " ";
String id = " ";
String name = " ";
try {
Socket skt = new Socket("localhost", 1234);
out = new PrintWriter(skt.getOutputStream(), true);
while (name.equals("exit")) { //never ending menu
System.out.print("Please enter name: ");
name = sc.nextLine();
System.out.print("Please enter ID Number: ");
id = sc.nextLine();
student = name +" - "+ id;
out.print(student);
}
} catch(Exception e) {
System.out.println("Whoops! It didn't work.");
} finally {
if (out != null) {
try {
out.close();
} catch (Exception e) {
}
}
}
}
}
Server:
import java.lang.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class Server {
public static void main(String args[]) {
Scanner sc = new Scanner (System.in);
ArrayList<String> collector = new ArrayList<String>();
String x = "";
try {
ServerSocket srvr = new ServerSocket(1234);
Socket skt = srvr.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream()));
x = in.readLine();
collector.add(x);
System.out.println("Server has added "+collector.get(collector.size()-1));
}
catch(Exception e) {
e.printStackTrace();
System.out.print("Whoops! It didn't work!\n");
}
}
}
Any idea what's wrong?

According to the "never ending menu"-condition select == 2, your initialization of int select = 0; and no other writings to select you will never execute the code in the loop.

Your loop will never execute as you have set select = 0

Related

Java basic concurrent communicator - does not fully accept connection

I want to create simple communicator with one server and few clients who could connect and send data to it. It works fine without any threads, with only one client, but once i try to incorporate concurrency it doesn't work. From client perspective there is some connection, I can send data, but there is no sign of receiving that data on server. Here is the server class:
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
public class MyServerSocket implements Runnable
{
private ServerSocket serverSocket;
public MyServerSocket() throws Exception
{
Random generator = new Random();
this.serverSocket = new ServerSocket(generator.nextInt(65000 - 60000) + 60000, 50, InetAddress.getByName("192.168.0.105"));
}
public InetAddress getSocketIPAddress()
{
return this.serverSocket.getInetAddress();
}
public int getPort()
{
return this.serverSocket.getLocalPort();
}
public void run()
{
while (true)
{
System.out.println("Running a thread");
try
{
String data = null;
Socket client = this.serverSocket.accept();
String clientAddress = client.getInetAddress().getHostName();
System.out.println("Connection from: " + clientAddress);
System.out.println("Here I am");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
String message = "";
while ((data = in.readLine()) != null && data.compareToIgnoreCase("quit") != 0)
{
message = ("\r\nMessage from " + clientAddress + ": " + data);
System.out.println(message);
out.write(message);
}
} catch (Exception e)
{
System.out.println("Something went wrong");
} finally
{
try
{
serverSocket.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}
Server main:
import java.lang.Thread;
public class Main
{
public static void main(String[] args)
{
try
{
MyServerSocket socket = new MyServerSocket();
Runnable runnable = new MyServerSocket();
System.out.println("Port number: " + socket.getPort() + " IP address: " + socket.getSocketIPAddress());
Thread thread = new Thread(runnable);
thread.start();
}catch (Exception e)
{
e.printStackTrace();
}
}
}
Client class:
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
public class ClientSocket
{
private Socket socket;
private Scanner scanner;
ClientSocket(InetAddress serverAddress, int serverPort) throws Exception
{
this.socket = new Socket(serverAddress, serverPort);
this.scanner = new Scanner(System.in);
}
public void sendData() throws Exception
{
String data;
System.out.println("Please type in the message. If you want to terminate the connection, type Quit");
PrintWriter out = new PrintWriter(this.socket.getOutputStream(), true);
do
{
data = scanner.nextLine();
out.println(data);
out.flush();
}while(data.compareToIgnoreCase("quit") != 0);
out.println();
}
}
Client main:
import java.net.InetAddress;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int port;
System.out.println("Provide port at which you will communicate with the server");
port = scanner.nextInt();
try
{
ClientSocket socket1 = new ClientSocket(InetAddress.getByName("192.168.0.105"), port);
socket1.sendData();
}catch(Exception e)
{
System.out.println("Could not connect to the server.");
}
}
}
Server somehow stops its working when is about to accept the client connection, while client works fine and seem to be connected to the server.
In server side, once you accept a client connection, you should new a thread to process this connection:
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
public class MyServerSocket implements Runnable {
private ServerSocket serverSocket;
public MyServerSocket() throws Exception {
Random generator = new Random();
this.serverSocket = new ServerSocket(generator.nextInt(65000 - 60000) + 60000, 50, InetAddress.getByName("192.168.0.105"));
}
public InetAddress getSocketIPAddress() {
return this.serverSocket.getInetAddress();
}
public int getPort() {
return this.serverSocket.getLocalPort();
}
public void run() {
while (true) {
System.out.println("Running a thread");
try(Socket client = this.serverSocket.accept()) {
// new thread to process this client
new Thread(() -> {
try {
String data = null;
String clientAddress = client.getInetAddress().getHostName();
System.out.println("Connection from: " + clientAddress);
System.out.println("Here I am");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
String message = "";
while (true) {
if (!((data = in.readLine()) != null && data.compareToIgnoreCase("quit") != 0)) break;
message = ("\r\nMessage from " + clientAddress + ": " + data);
System.out.println(message);
out.write(message);
}
} catch (IOException e) {
System.out.println("Something went wrong");
}
}).start();
} catch (Exception e) {
System.out.println("Something went wrong");
}
}
}
}
Ok, somehow I solved that problem, but still I need to understand how does it work:
Accepting connection inside try block, without finally block (nor try with resources) so socket is opened all the time.
Modified main method so there is no threads or runnable objects at all in it. The whole process is done within the class:
Code:
public class Main
{
public static void main(String[] args)
{
try
{
MyServerSocket socket = new MyServerSocket();
System.out.println("Port number: " + socket.getPort() + " IP address: " + socket.getSocketIPAddress());
socket.run();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
If anyone could point me out mistakes that are still in this final version of code I'll be grateful.

How to access a string called "numberPart" from a different file (multithreaded java socket programming)

There is a string called numberPart inside a thread class called ServerRecieve. The location where .start() is being called is inside of a different class called Server.
The 'numberPart' will eventually be used as a port for file transferring later on.
My question is: How do I access the numberPart variable inside of the class called Server?
Screenshot of code running (server on left window, client on the right):
server on left window, client on the right
In the left window of the screenshot (server) you can see the that the first port number of the right window's command line argument which is 4021 being sent via a text message, and the server successfully receives it with the message "File transfer port found: 4021". Unfortunately this variable is located inside a different class. I would like to know how to access that variable inside the class called Server.
ServerRecieve code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class ServerRecieve extends Thread
{
Socket servSocket;
boolean m_bRunThread = true;
boolean ServerOn = true;
public ServerRecieve(Socket s)
{
super();
servSocket = s;
}
public void run()
{
while(true)
{
try
{
BufferedReader readFromClient = new BufferedReader(new InputStreamReader(servSocket.getInputStream()));
String fromClient = readFromClient.readLine();
String a = fromClient;
int i;
for(i = 0; i < a.length(); i++)
{
char c = a.charAt(i);
if( '0' <= c && c <= '9' )
{
break;
}
}
String alphaPart = a.substring(0, i);
String numberPart = a.substring(i);
System.out.println("Recieved from client: " + alphaPart +"\n");
System.out.println("File transfer port found: " + numberPart + "\n");
//String[] filePortNumber = null;
//filePortNumber[0] = numberPart;
// Server thing = new Server(filePortNumber);
if(fromClient.equals(null))
{
System.exit(0);
}
OutputOptions();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
}
}
}
void OutputOptions()
{
System.out.println("Enter an option ('m', 'f', 'x'): ");
System.out.println("(M)essage (send)");
System.out.println("(F)ile (request) ");
System.out.println("e(X)it ");
}
}
Server source:
import java.io.*;
import java.net.*;
import java.util.*;
import javax.imageio.IIOException;
public class Server
{
private String[] serverArgs;
public Socket socket;
public Socket fileSocket;
public boolean keepRunning = true;
public int ConnectOnce = 0;
public String option = "";
public boolean isConnected = false;
public String FILE_TO_SEND = "/Users/nanettegormley/Documents/workspace/assignment2/src/servers/cdm.jpg";
public Server(String[] args) throws IOException
{
// set the instance variable
this.serverArgs = args;
if(ConnectOnce == 0)
{
int port_number1 = Integer.valueOf(serverArgs[1]);
ServerSocket serverSocket = new ServerSocket(port_number1);
socket = serverSocket.accept();
ConnectOnce = 4;
isConnected = true;
}
}
public String[] serverRun2(String[] args) throws IOException
{
serverArgs = args;
serverArgs = Arrays.copyOf(args, args.length);
serverSend.start();
return serverArgs;
}
Thread serverSend = new Thread()
{
public void run()
{
OutputOptions();
while(isConnected)
{
try
{
ServerRecieve serverThread = new ServerRecieve(socket);
serverThread.start();
// input the message from standard input
BufferedReader input2= new BufferedReader(new InputStreamReader(System.in));
option = input2.readLine();
if(option.equals("m") || option.equals("M"))
{
StandardOutput();
}
if(option.equals("f") || option.equals("F"))
{
FileTransferSend();
}
if(option.equals("x") || option.equals("X"))
{
System.exit(0);
}
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
}
}
};
public void StandardOutput()
{
try
{
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
//creating message to send from standard input
String newmessage = "";
try
{
System.out.println("Enter your message: ");
// input the message from standard input
BufferedReader input2= new BufferedReader(new InputStreamReader(System.in));
String line = "";
line= input2.readLine();
newmessage += line + " ";
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
String sendMessage = newmessage;
bw.write(sendMessage + "\n");
bw.newLine();
bw.flush();
System.out.println("Message sent to client: "+sendMessage);
StandardInput();
//run();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
}
}
void FileTransferSend()
{
//connect to the filetransfer
try
{
System.out.println("Which file do you want? ");
Scanner scanner = new Scanner(System.in);
String filename = scanner.nextLine();
FileInputStream fis = new FileInputStream(new File(filename));
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(fileSocket.getOutputStream()));
int element;
while((element = fis.read()) !=1)
{
dos.write(element);
}
byte[] byteBuffer = new byte[1024]; // buffer
while(fis.read(byteBuffer)!= -1)
{
dos.write(byteBuffer);
}
OutputOptions();
// dos.close();
// fis.close();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
}
}
void OutputOptions()
{
System.out.println("Enter an option ('m', 'f', 'x'): ");
System.out.println("(M)essage (send)");
System.out.println("(F)ile (request) ");
System.out.println("e(X)it ");
}
public void StandardInput()
{
OutputOptions();
while(true)
{
try
{
// input the message from standard input
BufferedReader input2= new BufferedReader(new InputStreamReader(System.in));
String line2 = "";
option= input2.readLine();
if(option.equals("m") || option.equals("M"))
{
StandardOutput();
}
if(option.equals("f") || option.equals("F"))
{
FileTransferSend();
}
if(option.equals("x") || option.equals("X"))
{
System.exit(0);
}
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
finally
{
}
}
}
}
Full code with all files:
https://www.dropbox.com/s/0yq47gapsd3dgjp/folder33.zip?dl=0
My question is: What changes can I make to the code that would allow me to access numberPart while being inside Server?
EDIT: Is there a way to bump a question that hasn't gotten any answers or should I just delete this one and repost it somewhere?
I would think that you could use either a listener or callback pattern to solve this.
(I'm losing my Java memory now that I'm doing C# so please bear with me..)
interface PortAssignable {
public assignPort(int port);
}
Then have the Server class implement that interface
public Server implements PortAssignable {
...
}
And ServerReceive
// Constructor
public ServerRecieve(Socket s, PortAssignable portNotifyListener) {
_portNotifyListener = portNotifyListener;
... your other code ...
}
Make sure when you create an instance of ServerReceive, you pass in your Server instance, via this.
ServerRecieve serverThread = new ServerRecieve(socket, this);
Now, when you get your numberPart, your next line can be
_portNotifyListener.assignPort(numberPart);
How you choose to implement the assignPort method in your Server class is up to you.
P.S. I saw this question from /r/programming.

Passing variable to Java Thread (run() method)

I'm trying to pass the variable "name" from my main method to the run() method.
I've tried this way how can I pass a variable into a new Runnable declaration?
But I couldn't get it to work. How can I pass that variable? (I've inserted the other class needed to run the program in full.)
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.net.InetAddress;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
public class Server {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
try {
final int port = 8181;
ServerSocket server = new ServerSocket(port);
System.out.println("Server is up and running, waiting for clients to connect.");
while (true) {
Socket sock = server.accept();
System.out.println("A new user has connected");
System.out.println("Type \"LIST\" to get a list of commands");
System.out.println("Enter your Username"); final String name = input.nextLine();
System.out.println("Now go to the client console to enter your messages");
new Thread(new Client(sock)).start();
}
} catch (Exception e) {
System.out.println("An error occured.");
e.printStackTrace();
}
}
static class Client implements Runnable {
private Socket socket;
int id;
public Client(Socket sock)
{
id = 1;
socket = sock;
}
#Override
public void run() {
long jvmUpTime = ManagementFactory.getRuntimeMXBean().getUptime();
RuntimeMXBean mxBean = ManagementFactory.getRuntimeMXBean();
try {
Scanner in = new Scanner(socket.getInputStream());
PrintWriter out = new PrintWriter(socket.getOutputStream());
while (true) {
String data = in.nextLine();
System.out.println("User : " + data);
if (data.startsWith("LEAVENOW")) {
System.out.println("Client has left the server");
break;
}
if (data.startsWith("GETIP")) {
// System.out.println("Client connected from " +
// InetAddress.getLocalHost());
System.out.println("Client connected from " + InetAddress.getLocalHost());
}
if (data.startsWith("SERVERTIME")) {
System.out.println(mxBean.getUptime());
}
/*
* if (data.startsWith("SETNAME")) {
*
* Scanner input = new Scanner(System.in);
*
* System.out.println("Enter your Username"); final String
* name = input.nextLine();
* System.out.println("Press 1 to confirm your user name");
* int namenum = input.nextInt(); if (namenum == 1){
*
* System.out.println("name changed"); }
*
*
* }
*/
if (data.startsWith("LIST")) {
System.out.println("Here is a list of commands that the user can use in the server");
System.out.println(
"LEAVENOW = exit the server \nGETIP = Gets the IP address of the server \nSERVERTIME = The amount of milliseconds the server has been running \n ");
}
// send the line back to the client
// or whatever custom message we want
// out.println(line);
// out.flush();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
The additional class to run the full program
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class ClientInstance {
final static int port = 8181;
final static String host = "localhost";
/**
* #param args
* the command line arguments
*/
public static void main(String[] args) throws IOException {
try {
Socket sock = new Socket(host, port);
System.out.println("You connected to " + host);
System.out.println("Now enter your message ");
new Thread(new ClientWriter(sock)).start();
new Thread(new ClientReader(sock)).start();
} catch (Exception CannotConnect) {
System.err.println("Could not connect to the server please try again, if error proceeds restart IDE");
}
}
static class ClientWriter implements Runnable {
public Socket socket;
public ClientWriter(Socket sock) {
socket = sock;
}
public void run() {
try {
Scanner chat = new Scanner(System.in);
PrintWriter out = new PrintWriter(socket.getOutputStream());
while (true) {
String input = chat.nextLine();
out.println(input);
out.flush();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
static class ClientReader implements Runnable {
public Socket socket;
public ClientReader(Socket sock) {
socket = sock;
}
public void run() {
try {
/* Scanner scanner = new Scanner(socket.getInputStream());
//read data from client
while(true) {
String data = scanner.nextLine();
System.out.println("Received data! : " + data);
}
*/
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
So with #Berger advice I changed my code and edited this part. All I did was add the string name as a parameter just like I did with socket sock. However when I call the name variable in my run() method the string just prints null.
new Thread(new Client(sock, name)).start();
}
} catch (Exception e) {
System.out.println("An error occured.");
e.printStackTrace();
}
}
static class Client implements Runnable {
private Socket socket;
int id;
String name;
public Client(Socket sock, String name)
{
id = 1;
socket = sock;
name = name;
}
You need to assign your fields in a proper way. You need to do as below.
this.name = name;
You have two different variables named as name. One is local variable (method parameter) and another is instance field.
What you have done is by name = name; you are assiging String referenced by your local variable name to same local variable name, instead what you should be doing is to assign String referenced by local variable name to instance field name ( which is this.name ).

Unable to write input into a file

I have tried many times to read a user input and then write it to a file but I haven't find a solution. Here is my code...
The main class.
import java.util.HashMap;
import java.util.Scanner;
public class cShell{
static String Currentpath="C:\\";
public String Current = Currentpath;
static HashMap<String, ICommand> myhashData=new HashMap<String, ICommand>();
public static void main(String[] args)
{
myhashData.put("ltf", new cITF());
myhashData.put("nbc", new cNBC());
myhashData.put("gdb", new cGDB());
myhashData.put("Tedit", new cTedit());
String Input = "";
do{
System.out.print(Currentpath+"> ");
//String Input = "";
Scanner scan = new Scanner(System.in);
if(scan.hasNext()){
Input = scan.nextLine().trim();
}
if(Input.equals("exit")){
System.exit(0);
}
if(myhashData.containsKey(Input)){
ICommand myCommand=myhashData.get(Input);
myCommand.Execute();
}
else{
System.out.println("Invalid Command");
}
}while(!Input.equals("exit"));
}
}
This is the class that do the read and write.
import java.util.*;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
//import java.lang.System.*;
public class cTedit implements ICommand{
#Override
public void Execute() {
String filename = "";
System.out.println("Enter the file name to be edited");
Scanner scan = new Scanner(System.in);
if(scan.hasNext()){
filename = scan.nextLine();
}
String line = null;
try{
InputStreamReader ISR = new InputStreamReader(System.in);
//FileReader fileReader = new FileReader(ISR);
FileWriter fileWriter = new FileWriter(cShell.Currentpath+"\\"+filename);
BufferedReader bufferedReader = new BufferedReader(ISR);
System.out.println("Enter text into the file");
while((line = bufferedReader.readLine()) != null){
fileWriter.write(line);
}
bufferedReader.close();
}catch(FileNotFoundException ex){
System.out.println("Unable to open file '" + filename + "'");
}
catch(IOException ex){
System.out.println("Error reading file '" + filename + "'");
}
}
}
My problem is when I enter some text as user input, pressing enter doesn't stop me from entering inputs, but when I press Ctrl+z it ran into an infinite loop.
Try this one in cTedit class.
bufferedReader.readLine() will never return null in your case.
Type exit to come out of loop.
while((line = bufferedReader.readLine()) != null){
if(line.equals("exit")){
break;
}
fileWriter.write(line);
}
Use fileWriter.close() in the end.
Maybe that's not the source of your problem, but I don't think that you need to check the hasnext() condition to read a line :
if(scan.hasNext()){
filename = scan.nextLine();
}
just filename = scan.nextLine(); should be enough.
Use the following
if(Input.equals("exit") || Input.equals("")){
System.exit(0);
}
instead of
if(Input.equals("exit")){
System.exit(0);
}
In order to close the fileWriter after just before exiting add a method closeFile as below.
import java.util.;
import java.io.;
import java.nio.file.Files;
import java.nio.file.Path;
//import java.lang.System.*;
public class cTedit implements ICommand{
private FileWriter fileWriter;
#Override
public void Execute() {
// TODO Auto-generated method stub
String filename = "";
System.out.println("Enter the file name to be edited");
Scanner scan = new Scanner(System.in);
if(scan.hasNext()){
filename = scan.nextLine();
}
String line = null;
try{
InputStreamReader ISR = new InputStreamReader(System.in);
//FileReader fileReader = new FileReader(ISR);
fileWriter = new FileWriter(cShell.Currentpath+"\\"+filename);
BufferedReader bufferedReader = new BufferedReader(ISR);
System.out.println("Enter text into the file");
while((line = bufferedReader.readLine()) != null){
fileWriter.write(line);
}
bufferedReader.close();
}catch(FileNotFoundException ex){
System.out.println("Unable to open file '" + filename + "'");
}
catch(IOException ex){
System.out.println("Error reading file '" + filename + "'");
} finally {
fileWriter.close();
}
}
public void closeFile() {
fileWriter.close();
}
}
and then callCloseFile in cShell class just before exiting

Java Server Guessing Game

I'm creating a server where clients connect to play a guessing game they are also to get points from doing this.
My only problem at the moment is that whenever my client guesses the number correctly it jumps to the server and says 'server null'. I want the guessing game to continue until the client inputs 'goodbye' - on which his/her score is given.
Here is my code could you point out where I've gone wrong and advise me on how I would achieve what I want. I think the problem is in protocol I probably just need to put the while in the correct place, so that's up first. Thanks folks!
Just to add, the variables are named oddly I'm aware of this it was previously a knock knock joke server
Protocol
import java.util.*;
public class KKProtocol {
int guess = 0, number = new Random().nextInt(100) + 1;
int score = 0;
Scanner scan = new Scanner(System.in);
public String processInput(String theInput) {
String theOutput = null;
System.out.println("Please guess the number between 1 and 100.");
while (guess != number) {
try {
if ((guess = Integer.parseInt(scan.nextLine())) != number) {
System.out.println(guess < number ? "Higher..." : "Lower...");
}
else {
System.out.println("Correct!");
score = 1;
}
}
catch (NumberFormatException e) {
System.out.println("Please enter a valid number! If you want to Quit just say'Goodbye'");
}
}
return theOutput;
}}
Server
import java.net.*;
import java.io.*;
public class KKServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
boolean listening = true;
try {
serverSocket = new ServerSocket(4040);
} catch (IOException e) {
System.err.println("Could not listen on port: 4040.");
System.exit(-1);
}
System.err.println("Started KK server listening on port 4040");
while (listening)
new KKThread(serverSocket.accept()).start();
System.out.println("Accepted connection from client");
serverSocket.close();
}
}
Thread
import java.net.*;
import java.io.*;
import java.util.Scanner;
public class KKThread extends Thread {
private Socket mySocket = null;
public KKThread(Socket inSocket) { //super("KKThread");
mySocket = inSocket;
}
public void run() {
try {
PrintWriter out = new PrintWriter(mySocket.getOutputStream(), true);
Scanner in = new Scanner(mySocket.getInputStream());
String inputLine, outputLine;
KKProtocol kkp = new KKProtocol();
outputLine = kkp.processInput(null); // first time only
out.println(outputLine); // (Should be "Knock Knock")
while (true) {
inputLine = in.nextLine(); // read in client input
outputLine = kkp.processInput(inputLine); // get reply from protocol
out.println(outputLine); // send it out to socket
if (outputLine.equals("Bye"))
break;
}
out.close();
in.close();
mySocket.close();
} catch (Exception e) {
System.err.println("Connection reset"); //e.printStackTrace();
}
}
}
Client
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class KKClient {
public static void main(String[] args) throws IOException {
Socket kkSocket = null;
PrintWriter out = null;
Scanner in = null;
try {
kkSocket = new Socket("127.0.0.1", 4040);
out = new PrintWriter(kkSocket.getOutputStream(), true);
in = new Scanner(new InputStreamReader(kkSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection");
System.exit(1);
}
Scanner stdIn = new Scanner(System.in);
String fromServer = in.nextLine();
while (true) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("Bye."))
break;
out.println(stdIn.nextLine());
fromServer = in.nextLine();
}
out.close();
in.close();
stdIn.close();
kkSocket.close();
}
}
'
Why does it jump to the server and says 'server null'? How do I continue the guessing until the client inputs 'goodbye'?
You are currently not assigning the server response for the score in KKProtocol.processInput() so a null is returned instead resulting in the message that you see:
Server: null
You could use:
theOutput = Integer.toString(score);
Also your score is fixed at 1 so you may wish to devise a scoring system perhaps based on the number of guesses used.
In you processInput()method, you are not returning any value, but allways null.
It looks like that null value is transformed into the String "null" on output and sent to the client.

Categories