Send to particular client using hashmap java - java

I'm trying to send a message to a particular client e.g. client 1 wants to send a message to client 2. Client 1 sends a message to the sever, the sever computes the answer and sends it to client 2 who displays it.
I'm using a HashMap to store each client. It compiles, but when I run it, it crashed when sending the message and displays
Problem with Communication Server
I believe the error is in the loop where I'm sending the message but I can't see what's wrong with it, do I need separate code on the client side?
Server:
import java.net.*;
import java.util.*;
import java.io.*;
public class EchoServer2b extends Thread implements Runnable{
protected static Socket clientSocket;
static String [] logs = new String[100];
//protected static ArrayList<PrintWriter> writers = new ArrayList<PrintWriter>();
static HashMap<String, Socket> clients = new HashMap<String, Socket>();
static int arrayPos = 0;
static int i, clientCount = 0;
static String clientID;
static String receiver="",actualMessage="";
public static void main(String[] args) throws IOException{
ServerSocket serverSocket = null;
try{
serverSocket = new ServerSocket(10008);
System.out.println ("Connection Socket Created");
try {
while (true)
{
System.out.println ("Waiting for Connection");
new EchoServer2b (serverSocket.accept());
++clientCount;
clientID = Integer.toString(clientCount);
clients.put(clientID, clientSocket);
}
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
}
catch (IOException e)
{
System.err.println("Could not listen on port: 10008.");
System.exit(1);
}
finally{
try{
serverSocket.close();
}
catch (IOException e)
{
System.err.println("Could not close port: 10008.");
System.exit(1);
}
}
}
private EchoServer2b (Socket clientSoc){
clientSocket = clientSoc;
start();
}
public void run(){
System.out.println ("New Communication Thread Started");
try{
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("Client ID: " + clientID);
String inputLine;
while ((inputLine = in.readLine()) != null) { //reading
System.out.println(inputLine);
String message[]=inputLine.split(", ");
logs[arrayPos] = message[1]; //keep record of all commands sent to server
arrayPos++; //update array position
receiver=message[0];
actualMessage=message[1];
if (actualMessage.equals("Bye.")) //break if client enters 'Bye."
break;
if(actualMessage.equals("Logs.")){ //print out contents of logs if any client enters 'Logs'
for(i=0; i<arrayPos; i++){
System.out.println("Log"+ i + ": " + logs[i]);
}
break;
}
for (Map.Entry<String, Socket> entry: clients.entrySet()) {
String clientName = entry.getKey();
if(clientName.equals(receiver))
{
Socket socket = entry.getValue();
try {
PrintWriter receiverOut = new PrintWriter(socket.getOutputStream(), true);
//DataOutputStream receiverDOS = new DataOutputStream(socket.getOutputStream());
int x, y, result;
String num1, num2, operator;
String [] splitStrings = actualMessage.split(" ");
num1 = splitStrings[0];
x = Integer.parseInt(num1);
operator = splitStrings[1];
num2 = splitStrings[2];
y = Integer.parseInt(num2);
switch(operator){
case "+":
result = x + y;
System.out.println ("Server: " + result);
receiverOut.println(result);
break;
case "-":
result = x - y;
System.out.println ("Server: " + result);
receiverOut.println(result);
break;
case "*":
result = x * y;
System.out.println ("Server: " + result);
receiverOut.println(result);
break;
case "/":
result = x / y;
System.out.println ("Server: " + result);
receiverOut.println(result);
break;
default:
System.out.println("Please enter a more simple equation using one of the 4 main operators i.e. '+, -, *, /'");
break;
}
receiverOut.flush();
receiverOut.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
out.flush();
out.close();
in.close();
clientSocket.close();
}
catch (IOException e){
System.err.println("Problem with Communication Server");
e.printStackTrace();
System.exit(1);
}
}
public void sendMessage(String receiver, String actualMessage) {
}
}
Client:
import java.io.*;
import java.net.*;
public class EchoClientB {
static boolean flag = true;
public static void main(String[] args) throws IOException{
String serverHostname = new String ("127.0.0.1");
if (args.length > 0)
serverHostname = args[0];
System.out.println ("Attemping to connect to host " + serverHostname + " on port 10008.");
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try{
echoSocket = new Socket(serverHostname, 10008);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
}catch (UnknownHostException e){
System.err.println("Don't know about host: " + serverHostname);
System.exit(1);
} catch (IOException e){
System.err.println("Couldn't get I/O for " + "the connection to: " + serverHostname);
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput = "";
System.out.println ("Type Message (\"Bye.\" to quit)");
//System.out.println("Enter a simple math equation i.e. 2 + 2 separated by a space…");
System.out.println("Enter the ID of the client you want to send the message to and a simple equation.");
System.out.println("Eg:2, 2 + 2 (with each element of the equation separated by a space…)");
while(true){
if(userInput.equals("Bye.")){
break;
}
if((userInput = stdIn.readLine()) != null){
out.println(userInput);
userInput = in.readLine();
System.out.println("echo: " + userInput);
System.out.println("Enter the ID of the client you want to send the message to and a simple equation.");
System.out.println("Eg:2, 2 + 2 (with each element of the equation separated by a space…)");
out.flush();
}
else if(in.ready()){
userInput = in.readLine();
System.out.println("echo: " + userInput);
System.out.println("Enter the ID of the client you want to send the message to and a simple equation.");
System.out.println("Eg:2, 2 + 2 (with each element of the equation separated by a space…)");
out.flush();
}
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}

In the server run method, at the end of the code where you are sending a message to one of the clients, you have
out.flush();
out.close();
in.close();
clientSocket.close();
}
}
catch (IOException e){
System.err.println("Problem with Communication Server");
System.exit(1);
}
This is closing the socket, and it why you are getting the exception. You may want to move this block to a place where you really do want to close the client's connection

You are getting a IOException because you're closing the stream you're trying to read from at line 140. I suggest you move all the steam closes out of while scope (line 142).

Related

Java beginner (Client-Server) : Sending multiple Integers to a socket

i have a very simple assignment in which i am supposed to send 2 integers into a socket, which sends their sum back to the "client".
this is my client:
int a,b,sum;
try
{
Socket Server_info = new Socket ("localhost", 15000);
BufferedReader FromServer = new BufferedReader (new InputStreamReader(Server_info.getInputStream()));
DataOutputStream ToServer = new DataOutputStream(Server_info.getOutputStream());
while (true)
{
System.out.println("Type in '0' at any point to quit");
System.out.println("Please input a number");
a = User_in.nextInt();
ToServer.writeInt(a);
System.out.println("Please input a second number");
b = User_in.nextInt();
ToServer.writeInt(b);
sum = FromServer.read();
System.out.println("the sum of " +a+ " and " +b+ " is: " +sum );
if (a==0 || b==0)
break;
}
this is my socket handler:
int num1=0 ,num2=0, sum;
try
{
BufferedReader InFromClient = new BufferedReader (new InputStreamReader(soc_1.getInputStream()));
DataOutputStream OutToClient = new DataOutputStream(soc_1.getOutputStream());
while (true)
{
num1 = InFromClient.read();
num2 = InFromClient.read();
sum = num1 + num2 ;
OutToClient.writeInt(sum);
}
}
catch (Exception E){}
After the first Integer input upon running the client i get this:
Type in '0' at any point to quit
Please input a number
5
Connection reset by peer: socket write error
i think the problem lays at the socket receiving side, i must be doing something wrong. any suggestions?
You can use DataInputStream and DataOupStream objects but I find it simpler to user a pair of Scanner and PrintWriter objects both at the server side and client side. So here is my implementation of the solution to the problem:
The Server Side
import java.io.*;
import java.net.*;
import java.util.*;
public class TCPEchoServer {
private static ServerSocket serverSocket;
private static final int PORT = 1234;
public static void main(String[] args)
{
System.out.println("Opening port...\n");
try {
serverSocket = new ServerSocket(PORT);
}
catch (IOException ioex){
System.out.println("Unable to attach to port!");
System.exit(1);
}
handleClient();
}
private static void handleClient()
{
Socket link = null; //Step 2
try {
link = serverSocket.accept(); //Step 2
//Step 3
Scanner input = new Scanner(link.getInputStream());
PrintWriter output = new PrintWriter(link.getOutputStream(), true);
int firstInt = input.nextInt();
int secondInt = input.nextInt();
int answer;
while (firstInt != 0 || secondInt != 0)
{
answer = firstInt + secondInt;
output.println(answer); //Server returns the sum here 4
firstInt = input.nextInt();
secondInt = input.nextInt();
}
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
System.out.println("Closing connection...");
link.close();
}
catch (IOException ie)
{
System.out.println("Unable to close connection");
System.exit(1);
}
}
}
}
The Client Side
import java.net.*;
import java.io.*;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class TCPEchoClient {
private static InetAddress host;
private static final int PORT = 1234;
public static void main(String[] args) {
try {
host = InetAddress.getLocalHost();
} catch (UnknownHostException uhEx) {
System.out.println("Host ID not found!");
System.exit(1);
}
accessServer();
}
private static void accessServer() {
Socket link = null; //Step 1
try {
link = new Socket(host, PORT); //Step 1
//Step 2
Scanner input = new Scanner(link.getInputStream());
PrintWriter output = new PrintWriter(link.getOutputStream(), true);
//Set up stream for keyboard entry
Scanner userEntry = new Scanner(System.in);
int firstInt, secondInt, answer;
do {
System.out.print("Please input the first number: ");
firstInt = userEntry.nextInt();
System.out.print("Please input the second number: ");
secondInt = userEntry.nextInt();
//send the numbers
output.println(firstInt);
output.println(secondInt);
answer = input.nextInt(); //getting the answer from the server
System.out.println("\nSERVER> " + answer);
} while (firstInt != 0 || secondInt != 0);
} catch (IOException e) {
e.printStackTrace();
}
catch (NoSuchElementException ne){ //This exception may be raised when the server closes connection
System.out.println("Connection closed");
}
finally {
try {
System.out.println("\n* Closing connection… *");
link.close(); //Step 4.
} catch (IOException ioEx) {
System.out.println("Unable to disconnect!");
System.exit(1);
}
}
}
}
The problem is that you mix streams and readers.
In order to successfully pass integers from client to server, for example with Data[Input/Output]Stream you should use:
// Server side
final DataInputStream InFromClient = new DataInputStream(soc_1.getInputStream());
final DataOutputStream OutToClient = new DataOutputStream(soc_1.getOutputStream());
// than use OutToClient.writeInt() and InFromClient.readInt()
// Client side
final DataInputStream FromServer = new DataInputStream(Server_info.getInputStream());
final DataOutputStream ToServer = new DataOutputStream(Server_info.getOutputStream());
// than use ToServer.writeInt() and FromServer.readInt()
If you let's say send an int from client to server (in this case using DataOutputStream.writeInt), it is very important to read the data with the corresponding decoding logic (in our case DataInputStream.readInt).

Why is my networked Java code skipping the output on every other round?

I have a threaded java client/server pair, and it's behaving really strange . Here is the server side :
public class sample_server {
private static int port=4444, maxConnections=0;
// Listen for incoming connections and handle them
public static void main(String[] args) {
int i=0;
try{
ServerSocket listener = new ServerSocket(port);
Socket server;
while((i++ < maxConnections) || (maxConnections == 0)){
doComms connection;
server = listener.accept();
doComms conn_c = new doComms(server);
Thread t = new Thread(conn_c);
t.start();
}
} catch (IOException ioe) {
System.out.println("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
}
}
class doComms implements Runnable {
private Socket server;
private String line,input;
doComms(Socket server) {
this.server=server;
}
public void run () {
input="";
try {
// Get input from the client
DataInputStream in = new DataInputStream (server.getInputStream());
PrintStream out = new PrintStream(server.getOutputStream());
while((line = in.readLine()) != null && !line.equals(".")) {
java.util.Date date = new java.util.Date();
String timeString = String.valueOf((date.getTime()));
input=input + line + timeString;
out.println("I got:" + line + " " + timeString + "\n");
}
// Now write to the client
System.out.println("Overall message is:" + input);
out.println("Overall message is:" + input);
server.close();
} catch (IOException ioe) { /* ETC BOILERPLATE */
And this is my client code :
public class sample_client {
public static void main(String[] args) throws IOException {
String serverHostname = new String ("127.0.0.1");
if (args.length > 0)
serverHostname = args[0];
System.out.println ("Attemping to connect to host " +
serverHostname + " on port 10007.");
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
// echoSocket = new Socket("taranis", 7);
echoSocket = new Socket(serverHostname, 4444);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + serverHostname);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: " + serverHostname);
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
System.out.print ("input: ");
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
System.out.print ("input: ");
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
//END OLD CODE
}
}
When I run this code, on the clients it only displays the full "echo" line on every other round, like so :
input: hi
echo: I got:hi 1430872840921
input: ok
echo:
input: hi
echo: I got:ok 1430872842861
input: ok
echo:
input: hi
echo: I got:hi 1430872846214
input: ok
echo:
input:
thanks
PrintStream out = new PrintStream(server.getOutputStream());
You need the autoflush parameter here too, just as in the client where you construct the PrintWriter.
Or else call flush() after every println() in the server, if you can be bothered.

how to close a buffered reader when in mid communication

I need a bufferread to work with a client which closes when the word "CLOSE". THE client closes, I just can't get the sever to close once messages have been sent through it.
Heres what code I have:
`
import java.io.*;
import java.net.*;
class TCPClient2 {
public static void main(String argv[]) throws Exception {
String sentence;
String modifiedSentence;
BufferedReader inFromUser
= new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("143.53.30.136", 49250);//port number and ip address of client
DataOutputStream outToServer
= new DataOutputStream(clientSocket.getOutputStream());
InputStream sin = clientSocket.getInputStream();
// Just converting them to different streams, so that string handling becomes easier.
DataInputStream inFromServer = new DataInputStream(sin);
try {
do {
System.out.print("Enter message : ");
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
//Question B4
//if statement for closing the socket connection
if (sentence.equals("CLOSE")) {
clientSocket.close();
//closes client socket
System.out.println("Socket Closed");
//prints socket closed to tell user socket has closed
System.exit(0);
}
outToServer.writeBytes(sentence + '\n');
System.out.print("Message sent! please wait for server message: ");
modifiedSentence = inFromServer.readUTF();
System.out.println("FROM SERVER: " + modifiedSentence);
} while (!sentence.equals("CLOSE"));
} catch (IOException e) {
}
clientSocket.close();
}
}`
AND the server:
`
/*
chris and paul
*/
import java.io.*;
import java.net.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TCPMultiThreadServer {
private static ServerSocket welcomeSocket;
//port number the server is using
private static final int PORT = 49250;
private static int clientNo =1;
public static void main(String argv[]) throws Exception
{
System.out.println("Opening port...\n");
try
{
// ServerSocket listens for new connections on specified port
welcomeSocket = new ServerSocket(PORT);
do
{
Socket client = welcomeSocket.accept();
System.out.println("\nNew client accepted.\n");
//Create a thread to handle communication with
//this client and pass the constructor for this
//thread a reference to the relevant socket...
TCPMultiThreadServer.ClientHandler handler =
new TCPMultiThreadServer().new ClientHandler(client,clientNo);
handler.start(); // Calls run() method in ClientHandler
clientNo++;
} while (true);
} catch (IOException e) {}
}
// Original work not credited
class ClientHandler extends Thread
{
private Socket client;
private BufferedReader inFromClient;
private BufferedReader text_to_Client;
private DataOutputStream outToClient;
private FileWriter Filestream;
private BufferedWriter out;
public int clientNo;
public boolean stopping;
//part A question 4, adding buffer string array to the program
private String[] buffer; //creation of buffer string array.
private int bufferI; // Index of the last thing inserted into the array
public ClientHandler(Socket socket, int clientNos)
{
//Set up reference to associated socket
client = socket;
clientNo= clientNos;
try
{
// Gets access to input/output stream of socket
inFromClient =
new BufferedReader(new InputStreamReader
(client.getInputStream()));
text_to_Client =
new BufferedReader(new InputStreamReader(System.in));
outToClient =
new DataOutputStream(client.getOutputStream());
} catch(IOException e) {}
}
public void run()
{
try
{
stopping = false;
//Question A4 buffer continued
buffer = new String[4];
//generates buffer string array containing 4 strings
bufferI = 0;
// make sure bufferIndex = 0
String clientSentence;
Thread mythread = Thread.currentThread();
do
{
//Accept message from client on socket's input stream
OutputStream sout = client.getOutputStream();
// Just converting them to different streams, so that string
// handling becomes easier.
DataOutputStream text_to_send = new DataOutputStream(sout);
clientSentence = inFromClient.readLine();
System.out.println("Message received from client number " +
clientNo + ": "+ clientSentence);
// String to be scanned to find the pattern.
String line = clientSentence;
String pattern = "[C][L][O][S][E]";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
//if (m.find( )) {
// System.out.println("Found value: " + m.find() );
// System.out.println("Found value: " + m.group(1) );
//System.out.println("Found value: " + m.group(2) );
//} else {
// System.out.println("NO MATCH");
//}
//part B question 4 close command
//if statement for closing the socket connection if it is equal to close
if(m.matches())
{ //prints socket closed to tell user socket has closed
System.out.println("Socket connection to client number "
+ clientNo + " closed");
try
{
} catch(Exception e) {}
out.flush();
out.close(); // Close the file handler
client.close(); // Close the connection with the client,
clientNo--; // Decrement the number of clients
}
else
{
//part A question 4, adding buffer string array to the program
// looks to see if the buffer string array is full
//and also looks to see if bufferIndex is in range
if (bufferI > buffer.length-1)
{
// Print BUFFER FULL
System.out.println("BUFFER FULL");
// Clear clientSentence string
clientSentence = " ";
// For loop which travels through the buffer array of string
for (int i=0; i<buffer.length; i++)
{
// Append buffer element to clientSentence string
clientSentence += buffer[i] + " , ";
buffer[i] = null; // makes the buffer null
}
bufferI = 0; // Reset bufferI back to 0 so writing to the buffer can restarted
// prints buffer cleared back to the clients
text_to_send.writeUTF("BUFFER CLEARED :" +
clientSentence);
}
else
{
buffer[bufferI] = clientSentence;
System.out.println("Buffer " + bufferI+ ": " +
buffer[bufferI]);
bufferI++;
System.out.println("Enter Message: ");
// Reads message from server interface
// and sends it to the client
clientSentence = text_to_Client.readLine();
text_to_send.writeUTF(clientSentence);
System.out.println("Your message: " +
clientSentence);
}
}
if (mythread.activeCount() == 2 &&
(clientNo ==0 || clientNo >0) &&
clientSentence.equals("CLOSE"))
{
System.exit(0);
}
} while(!clientSentence.equals("CLOSE"));
client.close();
} catch(IOException e) {}
}
}
}
`

java socket programming blocking on read and write to and from server&client

i have client server socket programming in java .
Server: Multi-threading server to serve the client for math calculations ,eg: sum of all numbers provided from client etc....
client: is to connect to the server and select specif math operations addition,subtraction ...
etc ,and provide the numbers to the server to return the result,and maybe the results is single value or maybe the result from server is array of numbers and depends on the type of the operation...
my Problem is: reading and writing blocking from server to client and vice-versa
eg:
**server->client :*** Welcome to the Calculation Server
server->client: "*** Please type in the num of rows: \n"
client->server: the user insert num of rows and send it to server
server->client: "*** Please type in the num of cols: \n"
client->server: the user insert num of columns and send it to server
server->client:writer.write("Enter the elements of first matrix");
client->server: at the client side it blocks or hang i dont know y???**
the server send
part of server code
import java.net.*;
import java.io.*;
class server_thread extends Thread
{
protected Socket clientSocket;
public static void main(String[] args) throws IOException
{
ServerSocket serverSocket = null;
int port=10008;
try {
serverSocket = new ServerSocket(port);
System.out.println ("Connection Socket Created on port : "+port);
try {
while (true)
{
System.out.println ("Waiting for Connection");
new server_thread (serverSocket.accept());
}
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
}
catch (IOException e)
{
System.err.println("Could not listen on port: 10008.");
System.exit(1);
}
finally
{
try {
serverSocket.close();
}
catch (IOException e)
{
System.err.println("Could not close port: 10008.");
System.exit(1);
}
}
}
private server_thread (Socket clientSoc)
{
clientSocket = clientSoc;
start();
}
public void run()
{
System.out.println ("New Communication Thread Started");
try {
BufferedReader reader =
new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
BufferedWriter writer=
new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
String sinput_row, sinput_col,srow_count, scol_count;
int row_count, col_count;
writer.write("*** Welcome to the Calculation Server ( ***\r\n");
////////////////////////////////////////////////////////////////////////////////////////////////
writer.write("*** Please type in the num of rows: \n");
writer.flush();
sinput_row = reader.readLine().trim();
int input_row=Integer.parseInt(sinput_row);
System.out.println("num of rows got:"+input_row);
//////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
writer.write("*** Please type in the num of cols: \n");
writer.flush();
sinput_col = reader.readLine().trim();
int input_col=Integer.parseInt(sinput_col);
System.out.println("num of Cols got:"+input_col);
//////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
writer.write("Enter the elements of first matrix");
writer.flush();
int first[][] = new int[input_row][input_col];
int second[][] = new int[input_row][input_col];
int sum[][] = new int[input_row][input_col];
for ( row_count = 0 ; row_count < input_row ; row_count++ )
for ( col_count = 0 ; col_count < input_col ; col_count++ )
{
String s_matrix1_element=reader.readLine().trim();
int matrix1_element=Integer.parseInt(s_matrix1_element);
first[row_count][col_count] = matrix1_element;
}
// the rest of code is ommited for simplicty of analysis
////////////////////////////////////////////////////////////////////////////////////////////////
//int result=num1+num2;
System.out.println("Addition operation done " );
writer.flush();
writer.write("");
//writer.write("\r\n=== Result is : "+result);
writer.flush();
clientSocket.close();
}
catch (IOException e)
{
System.err.println("Problem with Communication Server");
System.exit(1);
}
}
}
and here is client code :
import java.io.*;
import java.net.*;
import java.util.*;
public class client_thread {
public static void main(String argv[])
{
try{
Socket socketClient= new Socket("localhost",10008);
System.out.println("Client: "+"Connection Established");
BufferedReader reader =
new BufferedReader(new InputStreamReader(socketClient.getInputStream()));
BufferedWriter writer=
new BufferedWriter(new OutputStreamWriter(socketClient.getOutputStream()));
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String serverMsg;
String userInput;
writer.flush();
serverMsg = reader.readLine();
System.out.println("from server: " + serverMsg);
while((serverMsg = reader.readLine()) != null )
{
System.out.println("from server inside loop: " + serverMsg);
userInput = stdIn.readLine();
writer.write(userInput+"\r\n");
writer.flush();
}
}catch(Exception e){e.printStackTrace();}
}
}
so the problem
Your server writes:
writer.write("Enter the elements of first matrix");
And the client reads this using
while((serverMsg = reader.readLine()) != null)
So, since the server doesn't send any end of line, the clients waits for it.
Method 1:
Use 1 thread to handle your input stream and another thread to handle your output stream. Then you can do you read and write concurrently.
Method 2:
Use NIO (Non Blocking I/O).

Client to Server Messaging- Java

I would like some input on my relatively simple Client to server messaging program.
I think the Client part is OK, but the server bit is a bit broken.
The program actually sort of works (client can send messages to server).
I am having trouble putting a username + password on it (set it up for a default password + username , not storing multiple usernames + password) (currently using username:1, password:2).
And I would like for the server the receive the clients Ip, when it connects, if anyone has any spare time and some java experience it would be greatly appreciated.
Client:
import java.lang.*;
import java.io.*;
import java.net.*;
import java.util.Scanner;
class LongClient {
public static void main(String args[]) {
try {
Socket skt = new Socket("localhost", 1234);
BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream()));
Scanner kbReader = new Scanner(System.in);
PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
out.flush();
String message, servermessage;
InetAddress clientip = InetAddress.getLocalHost();
System.out.println("Preparing to chat...");
out.println("Client IP Address: " + clientip); // sends message to client giving ip
out.println("Client hostname: " + clientip.getHostAddress()); // send message to client giving computer name
do {
if (in.ready()) {
servermessage = in.readLine();
System.out.println("server>: " + servermessage);
}
message = kbReader.nextLine();
out.println(message);
out.println("Done");
//message="bye";
//out.println("bye");
Thread.currentThread().sleep(300);
} while (!message.equals("bye"));
out.close();
in.close();
} catch(Exception e) {
System.out.print(e);
}
}
}
Server:
import java.lang.*;
import java.io.*;
import java.net.*;
class LongServer {
public static void main(String args[]) throws IOException {
String data = "Welcome to My Server"; //welcome message
String data1 = "enter username"; //welcome message
String message;
int idstats1 = 0; //verifyed username
int idstats2 = 0; //verifyed password
int verify1 = 0;
try {
//Detecting the localhost's ip address
InetAddress localaddr = InetAddress.getLocalHost();
System.out.println ("Local IP Address : " + localaddr );
System.out.println ("Local hostname : " + localaddr.getHostAddress());
//Creating a server socket for connection
ServerSocket srvr = new ServerSocket(1234);
System.out.println("Waiting for connection on "+localaddr);
//Accept incoming connection
Socket skt = srvr.accept();
System.out.print("Server has connected!\n");
//get Input and Output streams
PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
out.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream()));
System.out.print("Sending string: '" + data + "'\n");
out.println(data); //sends welcome message
System.out.print("Sending string: '" + data1 + "'\n");
out.println(data1); //sends welcome message
message = in.readLine(); //reads the line typed in
while(verify1 == 0) {
if (idstats1 == 0) {
//if the client is not verifyed, it asks for a password
out.println("enter username");
}
if (idstats2 == 0) {
//if the client is not verifyed, it asks for a password
out.println("enter password");
}
if (message.equals("1")) {
//is the input is password, then the client is verifyed
out.println("Username accepted");
idstats1 = 1;
}
if (message.equals("2")) {
//is the input is password, then the client is verifyed
out.println("Password Accepted");
idstats2 = 1;
}
if (idstats1 == 1 && idstats2 == 1) {
verify1 = 1;
}
}
if (verify1 == 1) {
//if client is verifyed, it asks them to type a message and prints it to the console
out.println("enter a message");
System.out.println("client>"+message);
}
if (message.equals("bye")) {
//if the client enters "bye" then the server closes
out.println("Server closing");
System.out.println("server>Server closing");
}
while(!message.equals("bye")); {
out.close();
skt.close();
srvr.close();
}
} catch(BindException e) {
e.printStackTrace();
System.out.print("A server is already running on the same port.");
} catch(SocketException e) {
e.printStackTrace();
System.out.print("Client has disconnected rudely.");
} catch(Exception e) {
e.printStackTrace();
System.out.print(e);
}
}
}
Thanks, any help would be appreciated.

Categories