java socket programming chat - java

I'm Playing with a simple Client and Server application using socket, and i attempt to print a message in the console and get a response from the server but nothing shows up, i'm fairly new to sockets so i assume i have a logical error. It's a simple app that i want the client to prompt a user a user for a command (in my case an input string where the server will perform an action based on the 'thcharacter), send it to the server and just display the server response.I'm pretty sure my client isn't correct, can someone points out why i can't write anything from the client console.
package socketProgramming;
import java.io.*;
import java.net.*;
public class MyClient {
#SuppressWarnings("resource")
public static void main(String[] args) {
// TODO Auto-generated method stub
Socket socket= new Socket();
BufferedReader in = null;
String msg;
int port = 2222;
try {
System.out.println("CLient wants to connect on port: "+port);
socket = new Socket(InetAddress.getLocalHost().getHostAddress(), port);
System.out.println("The client is connected");
} catch (UnknownHostException e) {
System.exit(1);
} catch (IOException e) {
System.out.println("connect failed");
System.exit(1);
}
try{
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream output = new PrintStream(socket.getOutputStream());
String text = null;
output.print(text);
while ((text = input.readLine()) != null){
System.out.println("Client "+text);
}
socket.close();
System.out.println("Client Exiting");
}
catch(IOException e) {
System.out.println(e);
}}
}
package socketProgramming;
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String msg = "";
ServerSocket sSocket = null;
Socket clientSocket;
int port = 2222;//Integer.parseInt(args[0]);
try{
sSocket = new ServerSocket(port);
} catch(IOException e){
System.out.println(e);
}
while(true){
try {// listen for a connection from client and accept it.
System.out.println("Server is listenning on host: "
+InetAddress.getLocalHost().getHostAddress() +""
+ " and on port: "
+ port);
clientSocket = sSocket.accept();
System.out.println("Connection accepted");
BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// PrintWriter out =
// new PrintWriter(clientSocket.getOutputStream(), true);
PrintStream output = new PrintStream(clientSocket.getOutputStream());
msg = input.readLine();
if(msg != null){
if(msg.charAt(12)=='4'){
System.out.println("reading message "+msg+" ");
output.print("Bye");
sSocket.close();
System.out.println("Server exits");
}else{
if(msg.charAt(12)=='0'){
System.out.println("reading message "+msg+" ");
output.print("OK");
}else if (msg.charAt(12)=='1'){
System.out.println("reading message "+msg+" ");
//Should return IP address
output.print(clientSocket.getInetAddress());
}else if (msg.charAt(12)=='2'){
System.out.println("reading message "+msg+" ");
for(int i = 1; i<=10; ++i){
output.print(i);
output.print(" ");
}
}else if (msg.charAt(12)=='3'){
System.out.println("reading message "+msg+" ");
output.print("GOT IT");
}else{
System.out.println("*******************");
}
}
}
sSocket.close();
System.out.println("Server exits");
}
catch(IOException e) {
System.out.println("accept failed");
System.exit(1);
}
System.out.println("Hello world");
}
}
}

I took some liberties with your code and changed it a bit. It is by no means a perfect version of what you've supplied; however, it should get you pointed in the right direction. These were the problems that were solved:
MyClient was never prompting for user input.
MyServer was sending strings without newlines. MyClient was expecting strings with newlines.
In MyServer, the main socket was being closed at the bottom of the loop. I believe you intended to close the client socket so that the server would loop around and process another client.
In MyServer, you're checking the 13th character of the user's input (because you were indexing the 12th byte (zero based) of the string. I put in brute-force protection against checking the 13th byte of strings that are too short.
Again, I simply corrected certain problems in your code. I may have altered it beyond what your true goals actually are. These examples are intended to get you going on your way...
MyClient.java:
import java.io.*;
import java.net.*;
public class MyClient {
#SuppressWarnings("resource")
public static void main(String[] args) {
// TODO Auto-generated method stub
Socket socket = new Socket();
int port = 2222;
try {
System.out.println("CLient wants to connect on port: " + port);
socket = new Socket(InetAddress.getLocalHost().getHostAddress(), port);
System.out.println("The client is connected");
} catch (UnknownHostException e) {
System.exit(1);
} catch (IOException e) {
System.out.println("connect failed");
System.exit(1);
}
try {
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream output = new PrintStream(socket.getOutputStream());
// Get a line of input from the user.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String inputFromUser = br.readLine();
// Send that line of input to MyServer.
output.println(inputFromUser);
// Print out the response from MyServer.
System.out.println("SERVER RESPONSE: " + input.readLine());
socket.close();
System.out.println("Client Exiting");
} catch (IOException e) {
System.out.println(e);
}
}
}
MyServer.java:
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String msg = "";
ServerSocket sSocket = null;
Socket clientSocket;
int port = 2222;// Integer.parseInt(args[0]);
try {
sSocket = new ServerSocket(port);
} catch (IOException e) {
System.out.println(e);
}
while (true) {
try {// listen for a connection from client and accept it.
System.out.println("Server is listenning on host: " + InetAddress.getLocalHost().getHostAddress() + "" + " and on port: "
+ port);
clientSocket = sSocket.accept();
System.out.println("Connection accepted");
BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// PrintWriter out =
// new PrintWriter(clientSocket.getOutputStream(), true);
PrintStream output = new PrintStream(clientSocket.getOutputStream());
msg = input.readLine();
if (msg != null) {
if (msg.length() > 12 && msg.charAt(12) == '4') {
System.out.println("reading message " + msg + " ");
output.println("Bye");
System.out.println("Server exits");
} else {
if (msg.length() > 12 && msg.charAt(12) == '0') {
System.out.println("reading message " + msg + " ");
output.println("OK");
} else if (msg.length() > 12 && msg.charAt(12) == '1') {
System.out.println("reading message " + msg + " ");
// Should return IP address
output.println(clientSocket.getInetAddress());
} else if (msg.length() > 12 && msg.charAt(12) == '2') {
System.out.println("reading message " + msg + " ");
for (int i = 1; i <= 10; ++i) {
output.println(i + " ");
}
} else if (msg.length() > 12 && msg.charAt(12) == '3') {
System.out.println("reading message " + msg + " ");
output.println("GOT IT");
} else {
System.out.println("*******************");
// Invalid question from client, I guess.
output.println("HUH?");
}
}
// Make sure output is flushed to client. It will be, but
// just in case...
output.flush();
}
// We're done with this client. Close his socket.
clientSocket.shutdownOutput();
clientSocket.close();
System.out.println("Closed client socket");
}
catch (IOException e) {
System.out.println("accept failed");
e.printStackTrace();
System.exit(1);
}
System.out.println("Hello world");
}
}
}

The problem is that nobody is actually sending any lines. This is what your client does:
output.print(text); //sends null
while ((text = input.readLine()) != null){ //waits to receive a line
This last part is where your client stops because it waits for input that the server never sends. So here is where the server stops:
msg = input.readLine(); //waits to recieve a line
It never reads in null because you didn't send a line (e.g. ending with '\n'). You can easily fix this problem by replacing your output.print() calls with output.println() calls, so that your readers know the line has end and can be read in now.

Related

What is the problem of this code...? Java socket programming

I am coding client-server multithread calculator using java, socket programming.
There's any syntax error, but msgs cannot be received from server.
I think
receiveString = inFromServer.readLine()
does not works. This code is in Client program, in the while(true) loop.
What is the problem?
Here is my full code.
SERVER
import java.io.*;
import java.net.*;
public class Server implements Runnable
{
static int max = 5; //maximum thread's number
static int i = 0, count = 0; //i for for-loop, count for count number of threads
public static void main(String args[]) throws IOException
{
ServerSocket serverSocket = new ServerSocket(6789); //open new socket
File file = new File("src/serverinfo.dat"); //make data file to save server info.
System.out.println("Maximum 5 users can be supported.\nWaiting...");
for(i=0; i <= max; i++) { new Connection(serverSocket); } //make sockets - loop for max(=5) times
try //server information file writing
{
String dataString = "Max thread = 5\nServer IP = 127.0.0.1\nServer socket = 6789\n";
#SuppressWarnings("resource")
FileWriter dataFile = new FileWriter(file);
dataFile.write(dataString);
}
catch(FileNotFoundException e) { e.printStackTrace(); }
catch(IOException e) { e.printStackTrace(); }
}
static class Connection extends Thread
{
private ServerSocket serverSocket;
public Connection(ServerSocket serverSock)
{
this.serverSocket = serverSock;
start();
}
public void run()
{
Socket acceptSocket = null;
BufferedReader inFromClient = null;
DataOutputStream msgToClient = null;
String receiveString = null;
String result = "", sys_msg = "";
try
{
while(true)
{
acceptSocket = serverSocket.accept(); // 접속수락 소켓
count++;
inFromClient = new BufferedReader(new InputStreamReader(acceptSocket.getInputStream()));
msgToClient = new DataOutputStream(acceptSocket.getOutputStream());
System.out.println(count + "th client connected: " + acceptSocket.getInetAddress().getHostName() + " " + count + "/" + max);
System.out.println("Waiting response...");
while(true)
{
if (count >= max+1) // if 6th client tries to access
{
System.out.println("Server is too busy. " + max + " clients are already connected. Client access denied.");
sys_msg = "DENIED";
msgToClient.writeBytes(sys_msg);
acceptSocket.close();
count--;
break;
}
try{ msgToClient.writeBytes(result); }
catch(Exception e) {}
try{ receiveString = inFromClient.readLine(); }
catch(Exception e) // if receiveString = null
{
System.out.println("Connection Close");
count--;
break;
}
System.out.println("Input from client : " + receiveString);
try
{
if(receiveString.indexOf("+") != -1) { result = cal("+", receiveString); }
else if(receiveString.indexOf("-") != -1) { result = cal("-", receiveString); }
else if(receiveString.indexOf("/") != -1) { result = cal("/", receiveString); }
else if(receiveString.indexOf("*") != -1) { result = cal("*", receiveString); }
else if(receiveString.indexOf("+") == -1 || receiveString.indexOf("-") == -1 || receiveString.indexOf("*") == -1 || receiveString.indexOf("/") == -1) { result = "No INPUT or Invalid operation"; }
}
catch(Exception e){ result = "Wrong INPUT"; }
try{ msgToClient.writeBytes(result); }
catch(Exception e) {}
}
}
}
catch(IOException e) { e.printStackTrace(); }
}
}
private static String cal(String op, String recv) //function for calculating
{
double digit1, digit2; //first number, second number
String result = null;
digit1 = Integer.parseInt(recv.substring(0, recv.indexOf(op)).trim());
digit2 = Integer.parseInt(recv.substring(recv.indexOf(op)+1, recv.length()).trim());
if(op.equals("+")) { result = digit1 + " + " + digit2 + " = " + (digit1 + digit2); }
else if(op.equals("-")) { result = digit1 + " - " + digit2 + " = " + (digit1 - digit2); }
else if(op.equals("*")) { result = digit1 + " * " + digit2 + " = " + (digit1 * digit2); }
else if(op.equals("/"))
{
if(digit2 == 0){ result = "ERROR OCCURRED: Cannot be divided by ZERO"; }
else{ result = digit1 + " / " + digit2 + " = " + (digit1 / digit2); }
}
return result;
}
#Override
public void run() {
// TODO Auto-generated method stub
}
}
-----------------------------------------------------------------
CLIENT
import java.io.*;
import java.net.*;
public class Client {
public static void main(String args[]) throws IOException
{
Socket clientSocket = null;
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
BufferedReader inFromServer = null;
DataOutputStream msgToServer = null;
String sendString = "", receiveString = "";
try
{
clientSocket = new Socket("127.0.0.1", 6789); //make new clientSocket
inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
msgToServer = new DataOutputStream(clientSocket.getOutputStream());
System.out.println("Input exit to terminate");
System.out.println("Connection Success... Waiting for permission");
while(true)
{
receiveString = inFromServer.readLine();
if(receiveString.equals("DENIED"))
{
System.out.println("Server is full. Try again later.");
break;
}
else { System.out.println("Connection permitted."); }
System.out.print("Input an expression to calculate(ex. 3+1): ");
sendString = userInput.readLine();
if(sendString.equalsIgnoreCase("exit")) //when user input is "exit" -> terminate
{
clientSocket.close();
System.out.println("Program terminated.");
break;
}
try { msgToServer.writeBytes(sendString); }
catch(Exception e) {}
try { receiveString = userInput.readLine(); }
catch(Exception e) {}
System.out.println("Result: " + receiveString); //print result
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
You've set up your server socket stack wrong.
Your code will make 5 threads, each calling accept on a serversocket.
The idea is to have a single ServerSocket (and not 5, as in your example). Then, this single serversocket (running in a single thread that handles incoming sockets flowing out of this serversocket) will call .accept which will block (freeze the thread) until a connection is made, and will then return a Socket object. You'd then spin off a thread to handle the socket object, and go right back to the accept call. If you want to 'pool' (which is not a bad idea), then disassociate the notion of 'handles connections' from 'extends Thread'. For example, implement Runnable instead. Then pre-create the entire pool (for example, 10 threads), have some code that lets you 'grab a thread' from the pool and 'return a thread' to the pool, and now the serversocket thread will, upon accept returning a socket object, grab a thread from the pool (which will block, thus also blocking any incoming clients, if every thread in the pool is already taken out and busy handling a connection), until a thread returns to the pool. Alternatively, the serversocket code checks if the pool is completely drained and if so, will put on a final thread the job of responding to that client 'no can do, we are full right now'.
I'm not sure if you actually want that; just.. make 1 thread per incoming socket is a lot simpler. I wouldn't dive into pool concepts until you really need them, and if you do, I'd look for libraries that help manage them. I think further advice on that goes beyond the scope of this question, so I'll leave the first paragraph as an outlay of how ServerSocket code ought to work, for context.

Socket does not send data in while loop

I'm trying to do make simple network communication where a client sends a user input string to the server, which server then displays to the console.
When I send only one string, it works fine, but as soon as I wrap my user input code and send code in a while loop, the server receives nothing.
SERVER :
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(PORT);
System.out.println("Server now hosted on port " + PORT);
Socket s = serverSocket.accept();
System.out.println("A client has connected !");
BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
while(true){
//RECEIVE
int data;
String inString = "";
while((data=bis.read()) != -1){
inString += (char)data;
}
System.out.println("SLAVE : " + inString);
}
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Port déjà utilisé");
}finally {
try {
serverSocket.close();
System.out.println("Server closed");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Could not close port " + PORT);
}
}
CLIENT :
Scanner sc = new Scanner(System.in);
Socket s = null;
try {
s = new Socket("127.0.0.1", PORT);
BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
System.out.println("Connexion established !");
while(true){ // without this while loop, it works fine
String send = "";
System.out.print(">> ");
send = sc.nextLine();
bos.write(send.getBytes());
bos.flush();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Could not connect");;
}
finally {
try {
s.close();
System.out.println("Closing socket");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Could not close connection");;
}
}
System.out.println("End of client");
}
I expected the server to write any data it's reading from the socket as it's comming.
But it just does nothing.
I'm not quiet sure is the problem is comming from the server or the client.
The problem is with your while((data=bis.read()) != -1){ code.
It is looping until the EOS is received -1
When you don't have a client loop your Stream is closed, allowing the -1 to be sent, but not when you have a loop. Try printing with the server loop as below
while((data=bis.read()) != -1){
inString += (char)data;
if (((char)data) == '\n') {
System.out.println("SLAVE : " + inString);
inString = "";
}
}

Can't write an input to stdin in a Java program via command line, although I can do it on eclipse

I wrote a Server-Client model program in java, and it works great on eclipse. However, when I try to run the client via command line (in Windows 10), I can't write anything to stdin (while I can do it on Eclipse). Why is that?
Here is the client code (not the best one, I know):
import java.io.*;
import java.net.*;
public class MyEchoClient {
public static void main(String[] args) throws IOException{
Socket clientSocket = null; // the connection socket
PrintWriter out = null;
BufferedReader in = null;
String host = args[0], msg, tmp;
int port = Integer.decode(args[1]).intValue(), len;
System.out.println("Connecting to " + host + ":" + port);
try { // Trying to connect to a socket and initialize an output stream
clientSocket = new Socket(host, port); // host and port
out = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream(), "UTF-8"), true);
} catch (UnknownHostException e) {
System.out.println("Unknown host: " + host);
System.exit(1);
} catch (IOException e) {
System.out.println("Couldn't get output to " + host + " connection");
System.exit(1);
}
try { // Initialize an input stream
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(),"UTF-8"));
} catch (IOException e) {
System.out.println("Couldn't get input to " + host + " connection");
System.exit(1);
}
System.out.println("Connected to server!");
BufferedReader userIn = new BufferedReader(new InputStreamReader(System.in));
try{
while(true){
while(!userIn.ready()){
if (in.ready()){ // if server has something to write, when client does'nt have something to write
tmp=in.readLine();
len=tmp.length();
System.out.print(tmp);
if ((len>0 && tmp.charAt(tmp.length()-1)=='>') || tmp.contains("UNIDENTIFIED"))
System.out.println();
}
}
System.out.println();
msg = userIn.readLine();
if (msg==null) { break; }
out.println(msg);
tmp=in.readLine();
if (tmp.contains("~")) { break; }
System.out.println(tmp);
}
}
catch(IOException e){ System.out.println("Error with server connection."); }
System.out.println("Exiting...");
out.close();
in.close();
userIn.close();
clientSocket.close();
}
}
Edit: this is the input I get when I try to run MyEchoClient with the command (after connecting to a server on port 4000) java client.MyEchoClient 127.0.0.1 4000 :
Connecting to 127.0.0.1:4000
Connected to server!
(MyEchoClient is at folder named client).
And as I said, I can't write anything to stdin...

why won't my client side accept anymore input

why won't my client side accept anymore input, after inputing one FIX message. The client will send a FIX message to the server side, and the server will check for errors, and send back a message back to the client if it has errors or not on the FIX message.
The problem comes when I try to send another FIX message from the client side, prior to sending one, it won't allow me to send anything.
Client Program
public class TcpClient {
public static void main(String[] args) throws IOException {
String serverHostname = new String ("WA1235"); //127.0.0.1
if (args.length > 0)
serverHostname = args[0];
System.out.println ("Attemping to connect to host " +
serverHostname + " on port 57634.");
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
// echoSocket = new Socket("taranis", 7);
echoSocket = new Socket(serverHostname, 57634);
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(in.readLine());
System.out.println(in.readLine());
if (userInput.equals("Bye.")){
System.out.println("Exit program");
break;
}
getValueLog(parseFixMsg(userInput,userInput));
System.out.print ("input: ");
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
Server Program
public static void main(String[] args) throws IOException{
Scanner console = new Scanner(System.in);
System.out.println("Type in CSV file location: ");
//String csvName = console.nextLine();
String csvName = "C:\\Users\\Downloads\\orders.csv";
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(57634);
}
catch (IOException e)
{
System.err.println("Could not listen on port: 57635.");
System.exit(1);
}
Socket clientSocket = null;
System.out.println ("Waiting for connection.....");
try {
clientSocket = serverSocket.accept();
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
System.out.println ("Connection successful");
System.out.println ("Waiting for input.....");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
BufferedReader in = new BufferedReader(
new InputStreamReader( clientSocket.getInputStream()));
String inputLine, outputLine;
while ((inputLine = in.readLine()) != null)
{
System.out.println ("Server: " + inputLine);
if (inputLine.trim().equals("Bye.")) {
System.out.println("Exit program");
break;
}
Scanner input1 = new Scanner(new File(csvName));
Scanner input2 = new Scanner(new File(csvName));
Scanner input3 = new Scanner(new File(csvName));
Scanner input4 = new Scanner(new File(csvName));
String csvline = getCsvLineVal (getLocation34CSV(getTag34Value(Tag34Location(getTagCSV( parseFixMsg(inputLine ,inputLine))), getValueCSV( parseFixMsg(inputLine ,inputLine))), getVal34(input1, input2)), getCSVLine( input3, input4) );
outputLine = compareClientFixCSV( getTagCSV( parseFixMsg(inputLine ,inputLine)), getValueCSV(parseFixMsg(inputLine ,inputLine)), getCSVTag(csvline), getCSVValue(csvline));
out.println(outputLine);
input1.close();
input2.close();
input3.close();
input4.close();
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
method
public static String compareClientFixCSV(String[] cTag, String[] cValue, String[] csvTag, String[] csvValue){
int size = csvTag.length;
int size2 = csvTag.length;
int size3 = cValue.length;
int size4 = csvValue.length;
System.out.println("cTag size : " + size + ", csvTag: " + size2);
System.out.println("csvTag value : " + size3 + ", csvValue: " + size4);
String output = null;
for(int i = 0; i<= size-1; i++){
if(cTag[i].equals(csvTag[i]) == false ){
output = ("Error in tag " + cTag[i]);
}
else if(cValue[i].equals(csvValue[i]) == false){
output = ("Error in value " + cValue[i]);
}
else{
output = ("No errors");
}
}
return output;
}
Just a quick look at the code, I see the client waits for 2 lines:
System.out.println(in.readLine());
System.out.println(in.readLine());
and the server sends only 1:
out.println(outputLine);
May be that is the problem.
I'd also will enclose the reading part of the client in a try ... catch ... finally block, like this:
try
{
while (true)
{
System.out.print("input: ");
userInput = stdIn.readLine();
if (userInput == null) break;
out.println(userInput);
System.out.println(in.readLine());
System.out.println(in.readLine());
if (userInput.equals("Bye."))
{
System.out.println("Exit program");
break;
}
getValueLog(parseFixMsg(userInput,userInput));
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
// any of these lines could raise an exception as well.
out.close();
in.close();
stdIn.close();
echoSocket.close();
}

Connecting a Client to Multiple Servers in Java

I want a client to connect to more than one server. i.e. I want my client to send a number to server1 which squares the number and echoes it back to the client. However I want the client to then send this squared number to a second server listening on a different port.
I'm not sure how to implement this functionality, could I do this through threads or would I just open a second socket to server2?
Here is the code for my client.
import java.io.*;
import java.net.*;
public class ClientA {
public static void main(String[] args) {
String serverhost = "localhost";
int serverport = 6789;
Socket clientSocket = null;
DataOutputStream os = null;
BufferedReader is = null;
try {
clientSocket = new Socket(serverhost, serverport);
os = new DataOutputStream(clientSocket.getOutputStream());
is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + serverhost);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: " + serverhost);
} //end try
if (clientSocket == null || os == null || is == null) {
System.err.println( "An error has occured, please restart." );
return;
} //end if
try {
while ( true ) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String keyboardInput = br.readLine();
os.writeBytes( keyboardInput + "\n" );
int n = Integer.parseInt( keyboardInput );
if ( n == 0 ) {
break;
}
String responseLine = is.readLine();
System.out.println("Server returns its square as: " + responseLine);
}
os.close();
is.close();
clientSocket.close();
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
} //end try
} //end main
} //end class
Based on the info you've given, I don't see the need to make it a multi-threaded application as you're only sending (i.e. not receiving) data to the second server when you receive a reply from the first server. Just set up a second socket to the other address and send the data when you get it from the first server.

Categories

Resources