Client to Server Messaging- Java - 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.

Related

Server is automatically taking an input from the client instead of waiting in Java

UPDATE:
I tried hardcoding the password and letting the user be input, it just skipped the input part like this:
Please press one to sign in or two to sign up if you haven't already1
Please enter your credentials below
Username:
Password:
Your username and/or password are incorrect, access has been denied
UPDATE 2:
I tried the following 2 fixes and non worked:
Fix 1 client
System.out.println(inputFromServer.readUTF());
int choice = scan.nextInt();
outputToServer.writeInt(choice);
System.out.println(inputFromServer.readUTF());
String username = scan.nextLine();
outputToServer.writeUTF(username);
System.out.println(inputFromServer.readUTF());
scan.next();
String password = scan.nextLine();
outputToServer.writeUTF(password);
System.out.println(inputFromServer.readUTF());
fix 1 server:
outputToClient.writeUTF("Please enter your username");
Username = inputFromClient.readUTF();
outputToClient.writeUTF("Password:");
inputFromClient.readUTF();
Password = inputFromClient.readUTF();
fix 2 client:
System.out.println(inputFromServer.readUTF());
int choice = scan.nextInt();
scan.next();
outputToServer.writeInt(choice);
System.out.println(inputFromServer.readUTF());
String username = scan.nextLine();
outputToServer.writeUTF(username);
System.out.println(inputFromServer.readUTF());
String password = scan.nextLine();
outputToServer.writeUTF(password);
System.out.println(inputFromServer.readUTF());
fix 2 server:
outputToClient.writeUTF("Please enter your username");
Username = inputFromClient.readUTF();
outputToClient.writeUTF("Password:");
inputFromClient.readUTF();
Password = inputFromClient.readUTF();
I am writing a client-server code in Java where the client has to choose between signing in or signing up and then he needs to input his info accordingly, however, I am facing some bugs.
From the client-side, I have the following:
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class MultipleClient {
public static void main(String[] args) throws IOException {
try {
Scanner scan = new Scanner(System.in);
InetAddress ip = InetAddress.getByName("localhost");
Socket socket = new Socket(ip, 8189);
// Receiving input and sending output to Server
DataInputStream inputFromServer = new DataInputStream(socket.getInputStream());
DataOutputStream outputToServer = new DataOutputStream(socket.getOutputStream());
while (true) {
System.out.println(inputFromServer.readUTF());
int choice = scan.nextInt();
outputToServer.writeInt(choice);
System.out.println(inputFromServer.readUTF());
String username = scan.nextLine();
outputToServer.writeUTF(username);
System.out.println(inputFromServer.readUTF());
String password = scan.nextLine();
outputToServer.writeUTF(password);
System.out.println(inputFromServer.readUTF());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
While from the server-side, I have the following:
import java.io.*;
import java.text.*;
import java.util.*;
import java.net.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
public class MultipleServer {
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
ServerSocket serverSocket = new ServerSocket(8189);
// Server keeps on receiving new Clients
while (true) {
Socket clientSocket = null;
try {
// ServerSocket waits for a Client to connect
clientSocket = serverSocket.accept();
System.out.println("A new client is connected : " + clientSocket);
// Receiving input and sending output to Client
DataInputStream inputFromClient = new DataInputStream(clientSocket.getInputStream());
DataOutputStream outputToClient = new DataOutputStream(clientSocket.getOutputStream());
System.out.println("Assigning new thread for this client");
System.out
.println("-----------------------------------------------------------------------------------");
// Create a new Thread object for the Client
Thread thread = new ClientHandler(clientSocket, inputFromClient, outputToClient);
thread.start();
} catch (Exception e) {
clientSocket.close();
e.printStackTrace();
}
}
}
}
// ClientHandler class
class ClientHandler extends Thread {
final Socket clientSocket;
final DataInputStream inputFromClient;
final DataOutputStream outputToClient;
// Constructor
public ClientHandler(Socket clientSocket, DataInputStream inputFromClient, DataOutputStream outputToClient) {
this.clientSocket = clientSocket;
this.inputFromClient = inputFromClient;
this.outputToClient = outputToClient;
}
#Override
public void run() {
// Variables
String Username = "";
String Password = "";
int choice;
String toreturn;
while (true) {
try {
// The newInstance() call is a work around for some
// broken Java implementations
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
} catch (Exception ex) {
// handle the error
}
Connection conn = null;
try {
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test" + "?user=root&password=test");
} catch (SQLException ex) {
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
try {
outputToClient.writeUTF("Please press one to sign in or two to sign up if you haven't already");
choice = inputFromClient.readInt();
if (choice != 1 && choice != 0) {
outputToClient.writeUTF("Please choose one of the listed choices");
} else {
if (choice == 1) {
//here is where the problem is occuring
outputToClient.writeUTF("Please enter your credentials below\n");
outputToClient.writeUTF("Username:");
Username = inputFromClient.readUTF();
outputToClient.writeUTF("Password:");
Password = inputFromClient.readUTF();
String queryoneresult = "";
//execution isn't reaching this part so I don't think it is relevant but I included it anyway
ResultSet rs = null;
PreparedStatement stmt = conn
.prepareStatement("SELECT COUNT(Username)\n" + " FROM Authentication\n"
+ " WHERE Username = ? AND\n" + " Password = ? \n" + " LIMIT 0, 1");
stmt.setString(1, Username);
stmt.setString(2, Password);
rs = stmt.executeQuery();
if (stmt.execute()) {
rs = stmt.getResultSet();
}
ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
while (rs.next()) {
for (int i = 1; i <= columnsNumber; i++) {
if (i > 1)
System.out.print(" ");
String columnValue = rs.getString(i);
queryoneresult = rs.getString(i);
}
}
if (Integer.valueOf(queryoneresult) == 1) {
outputToClient.writeUTF("Username and password have been verified, you can now proceed ");
} else {
outputToClient
.writeUTF("Your username and/or password are incorrect, access has been denied");
}
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
My problem is that I am getting the following output:
Please press one to sign in or two to sign up if you haven't already
1
Please enter your credentials below
Username:
sergio
Password:
Your username and/or password are incorrect, access has been denied
so it seems like the server is automatically getting a response for the password and proceeding like this, had executions that looked like this too:
Please press one to sign in or two to sign up if you haven't already
1
Please enter your credentials below
Username:
Password:
sergio
Your username and/or password are incorrect, access has been denied
Any help would be appreciated.

Java Thread Bind Exception combined with address already in use error (client server using sockets)

There are two files (client file, server file) in this program that are supposed to be able to send and receive messages (utf-8 strings) to each other. Each file has a thread (one thread for client, one thread for server)
The client and the server connect on localhost with a port number (it should be the same port number when typing on the command prompt / mac terminal window)
However, the server is supposed to only send messages to all the other clients after receiving a message from a client. In other words, if a client sends a message to the server, the server cannot send that message back to the same client--it can only send messages to the different clients.
Another way to say it: Once a client is connected, it can send messages to the server. It will also receive from the server all messages sent from the other connected clients (not the messages sent from itself).
At runtime, there is supposed to be only one server (mac terminal / command prompt windows) but there can be multiple/infinite number of clients (mac terminal / command prompt windows)
Screenshot of error (server side):
Screenshot of error (client side):
Code of ChatServer.java:
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class ChatServer
{
private static Socket socket;
public static void main(String args[])
{
Thread ChatServer1 = new Thread ()
{
public void run ()
{
System.out.println("Server thread is now running");
try
{
int port_number1 = 0;
int numberOfClients = 0;
boolean KeepRunning = true;
if(args.length>0)
{
port_number1 = Integer.valueOf(args[0]);
}
System.out.println("Waiting for connections on port " + port_number1);
try
{
ServerSocket serverSocket = new ServerSocket(port_number1);
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println( "Listening for connections on port: " + ( port_number1 ) );
while(KeepRunning)
{
ServerSocket serverSocket = new ServerSocket(port_number1);
//create a list of clients
ArrayList<String> ListOfClients = new ArrayList<String>();
//connect to client
socket = serverSocket.accept();
//add new client to the list, is this the right way to add a new client? or should it be in a for loop or something?
ListOfClients.add("new client");
numberOfClients += 1;
System.out.println("A client has connected. Waiting for message...");
ListOfClients.add("new client" + numberOfClients);
//reading encoded utf-8 message from client, decoding from utf-8 format
String MessageFromClientEncodedUTF8 = "";
BufferedReader BufReader1 = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
String MessageFromClientDecodedFromUTF8 = BufReader1.readLine();
byte[] bytes = MessageFromClientEncodedUTF8.getBytes("UTF-8");
String MessageFromClientDecodedUTF8 = new String(bytes, "UTF-8");
//relaying message to every other client besides the one it was from
for (int i = 0; i < ListOfClients.size(); i++)
{
if(ListOfClients.get(i)!="new client")
{
String newmessage = null;
String returnMessage = newmessage;
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage + "\n");
System.out.println("Message sent to client: "+returnMessage);
bw.flush();
}
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (socket != null)
{
socket.close ();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
};
ChatServer1.start();
}
}
Code of ChatClient.java:
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class ChatClient
{
private static Socket Socket;
static int numberOfClients = 0;
public static void main(String args[])
{
//If I wanted to create multiple clients, would this code go here? OR should the new thread creation be outside the while(true) loop?
while (true)
{
String host = "localhost";
int numberOfClients = 0;
Thread ChatClient1 = new Thread ()
{
public void run()
{
try
{
//Client begins, gets port number, listens, connects, prints out messages from other clients
int port = 0;
int port_1number1 = 0;
int numberofmessages = 0;
String[] messagessentbyotherclients = null;
System.out.println("Try block begins..");
System.out.println("Chat client is running");
String port_number1= args[0];
System.out.println("Port number is: " + port_number1);
if(args.length>0)
{
port = Integer.valueOf(port_number1);
}
System.out.println("Listening for connections..");
System.out.println( "Listening on port: " + port_number1 );
Socket.connect(null);
System.out.println("Client has connected to the server");
for(int i = 0; i < numberOfClients; i++)
{
System.out.println(messagessentbyotherclients);
}
//client creates new message from standard input
OutputStream os = Socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
//creating message to send from standard input
String newmessage = "";
try
{
// input the message from standard input encoded in UTF-8 string format
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String line = "";
System.out.println( "Standard input (press enter then control D when finished): " );
while( (line= input.readLine()) != null )
{
newmessage += line + " ";
input=null;
}
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
//Sending the message to server
String sendMessage = newmessage;
bw.write(sendMessage + "\n");
bw.flush();
System.out.println("Message sent to server: "+sendMessage);
}
catch (IOException e)
{
e.printStackTrace();
}
}
};
ChatClient1.start();
}
}
}
These two errors have been covered many times and I've heard that the answer is to put the socket in a loop, which it already is in (while loop).
My question is: Is there a way to locate the errors before running it? Whenever I compile the program I don't get any errors in eclipse, but when I run it in the command prompt window / mac terminal, it does tell me that something is wrong. Or perhaps there's a line of code that I'm overlooking?
ServerSocket serverSocket = new ServerSocket(port_number1);
Place it once, before the while loop.

Send to particular client using hashmap 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).

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) {}
}
}
}
`

Categories