Overriding the run() method to accept a parameter from the command line - java

I'm trying to search a word (from a file) specified in the command line using client/server. Here is my code, however it displays nothing when the client part is run. To run the server, type -s <port number> <file.txt> and for the client, -c localhost <port number> <word to be searched> in the command line.
import java.net.*;
import java.util.*;
import java.io.*;
public class quotes {
public static InetAddress host;
public static ServerSocket serverSocket;
public static String target;
public static void main(String[] args) throws IOException {
if(args[0].equals("-c")){
Client(args);
target = args[3];
}
else if(args[0].equals("-s")){
System.out.println("Server");
Server(args);
}
}
#SuppressWarnings("resource")
public static void Client(String[] args) throws IOException{
String hostname = args[1];
if(hostname.equals("localhost")) host = InetAddress.getLocalHost();
else host = InetAddress.getByName(hostname);
int port = Integer.parseInt(args[2]);
Socket socket = new Socket(host, port);
Scanner input = new Scanner(System.in);
Scanner networkInput = new Scanner(socket.getInputStream());
PrintWriter networkOutput = new PrintWriter(socket.getOutputStream(), true);
Scanner userEntry = new Scanner(System.in);
String response;
networkOutput.println(target);
response = networkInput.nextLine();
while(!response.equals("|")){
System.out.println("\n " + response);
response = networkInput.nextLine();
}
}
public static void Server(String[] args) throws IOException {
int port = Integer.parseInt(args[1]);
String file = args[2];
serverSocket = new ServerSocket(port);
do {
Socket client = serverSocket.accept();
System.out.println("\nNew client accepted.\n");
ClientHandler3 handler = new ClientHandler3(client, file);
handler.start();
}while(true);
}
}
class ClientHandler3 extends Thread {
private Socket client;
private Scanner input;
private PrintWriter output;
private ArrayList<String> quotes;
public ClientHandler3(Socket socket, String file) {
client = socket;
try {
BufferedReader buffer = new BufferedReader(new FileReader(file));
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line = reader.readLine();
try {
int ctr = 0;
quotes = new ArrayList<String>();
while(line != null){
quotes.add(ctr, line);
ctr++;
line = buffer.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
input = new Scanner(client.getInputStream());
output = new PrintWriter(client.getOutputStream(), true);
}
catch(IOException e) {
e.printStackTrace();
}
}
public void run() {
String target;
String message = "";
target= args[3];
for(int i = 0; i<quotes.size(); i++){
if(quotes.get(i).toUpperCase().contains(target.toUpperCase())){
output.println(quotes.get(i));
}
}
output.println("|");
try {
if (client != null) {
System.out.println("Closing down connection...");
client.close();
}
}
catch(IOException e) {
System.out.println("Unable to disconnect!");
}
}
}
(Thanks to Sir JB Nizet for some modifications and advice) I'm having a problem in target= args[3]; in class ClientHandler3 because I know it makes no sense in overriding. I'm new in this field of programming and I need your help. Please help me figure things out. Thank you!
EDIT
import java.net.*;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.io.*;
public class quotes {
public static InetAddress host;
public static ServerSocket serverSocket;
public static void main(String[] args) throws IOException {
if(args[0].equals("-c")){
Client(args);
}
else if(args[0].equals("-s")){
System.out.println("SERVER KA!!!");
Server(args);
}
}
#SuppressWarnings("resource")
public static void Client(String[] args) throws IOException
String hostname = args[1];
String target, response;
if(hostname.equals("localhost")) host = InetAddress.getLocalHost();
else host = InetAddress.getByName(hostname);
int port = Integer.parseInt(args[2]);
target = args[3];
Socket socket = new Socket(host, port);
Scanner input = new Scanner(System.in);
Scanner networkInput = new Scanner(socket.getInputStream());
PrintWriter networkOutput = new PrintWriter(socket.getOutputStream(), true);
// Set up stream from keyboard entry...
Scanner userEntry = new Scanner(System.in);
networkOutput.println(target);
response = networkInput.nextLine();
while(!response.equals("|")){
// Display server's response to user ...
System.out.println("\n " + response);
response = networkInput.nextLine();
}
}
public static void Server(String[] args) throws IOException {
int port = Integer.parseInt(args[1]);
String file = args[2];
String target = "";
serverSocket = new ServerSocket(port);
do {
// Wait for client...
Socket client = serverSocket.accept();
System.out.println("\nNew client accepted.\n");
ClientHandler3 handler = new ClientHandler3(client, file, target);
handler.start();
}while(true);
}
}
class ClientHandler3 extends Thread {
private Socket client;
private Scanner input;
private PrintWriter output;
private ArrayList<String> quotes;
private String target;
public ClientHandler3(Socket socket, String file, String target) {
// Set up reference to associated socket...
client = socket;
try {
BufferedReader buffer = new BufferedReader(new FileReader(file));
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
this.target = reader.readLine();
String line = reader.readLine();
try {
int ctr = 0;
quotes = new ArrayList<String>();
while(line != null){
quotes.add(ctr, line);
ctr++;
line = buffer.readLine();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
input = new Scanner(client.getInputStream());
output = new PrintWriter(client.getOutputStream(), true);
}
catch(IOException e) {
e.printStackTrace();
}
}
public void run() {
String message = "";
target= input.nextLine();
for(int i = 0; i<quotes.size(); i++){
if(quotes.get(i).toUpperCase().contains(target.toUpperCase())){
output.println(quotes.get(i));
}
}
output.println("|");
try {
if (client != null) {
System.out.println("Closing down connection...");
client.close();
}
}
catch(IOException e) {
System.out.println("Unable to disconnect!");
}
}
}

Set target as a field of ClientHandler3 so you can use it inside run() method.
class ClientHandler3 extends Thread {
...
private String target;
...
and use:
this.target = reader.readLine();
just before
String line = reader.readLine();
line.

Related

Why did the server receive the first message but not the second message ("how are you")? (multithreaded java socket programming)

I am trying to create a text messaging program with three files (main function file, client file, server file)
If "-l" is present on the command line, it will run as a server, otherwise it will run as a client
Command line arguments to run server:
java DirectMessengerCombined -l 3000
Command line arguments to run client:
java DirectMessengerCombined 3000
All three files need to be able to access String args[] in the main function file because that is how it gets the port number
Screenshot of error (Server on left, client on right):
The problem with this screenshot is that the "how are you" message is never received by the server (left window)
Code of Server file (DirectMessengerServer):
import java.io.*;
import java.net.*;
import java.util.*;
import javax.imageio.IIOException;
public class DirectMessengerServer
{
private String[] serverArgs; // <-- added variable
private static Socket socket;
public boolean keepRunning = true;
int ConnectOnce = 0;
public DirectMessengerServer(String[] args) throws IOException
{
// set the instance variable
this.serverArgs = args;
run();
}
public String[] ServerRun(String[] args) throws IOException
{
//How do I get the String[] args in this method be able to access it in the run methods?
serverArgs = args;
serverArgs = Arrays.copyOf(args, args.length);
return serverArgs;
}
Thread ListeningLoop = new Thread();
//run method of ServerRecieve
public void run() throws IOException
{
try
{
if(ConnectOnce == 0)
{
int port_number1 = Integer.valueOf(serverArgs[1]);
ServerSocket serverSocket = new ServerSocket(port_number1);
socket = serverSocket.accept();
ConnectOnce = 4;
}
while(keepRunning)
{
//Reading the message from the client
//BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String MessageFromClient = br.readLine();
System.out.println("Message received from client: "+ MessageFromClient);
// ServerSend.start();
runSend();
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
}
}
Thread ServerSend = new Thread ();
//Run method of ServerSend
public void runSend()
{
while(keepRunning)
{
System.out.println("Server sending thread is now running");
try
{
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
//creating message to send from standard input
String newmessage = "";
try
{
// input the message from standard input
BufferedReader input= new BufferedReader(
new InputStreamReader(System.in));
String line = "";
line= input.readLine();
newmessage += line + " ";
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
String sendMessage = newmessage;
bw.write(sendMessage + "\n");
bw.flush();
System.out.println("Message sent to client: "+sendMessage);
run();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
}
}
}
}
Code of client (DirectMessengerClient):
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class DirectMessengerClient
{
private String[] clientArgs; // <-- added variable
private static Socket socket;
public boolean keepRunning = true;
public DirectMessengerClient(String[] args) throws IOException
{
// set the instance variable
this.clientArgs = args;
run(args);
}
public String[] ClientRun(String[] args)
{
clientArgs = args;
clientArgs = Arrays.copyOf(args, args.length);
return clientArgs;
}
Thread ClientSend = new Thread();
public void run(String args[]) throws IOException
{
System.out.println("Client send thread is now running");
while(keepRunning)
{
String port_number1= args[0];
System.out.println("Port number is: " + port_number1);
int port = Integer.valueOf(port_number1);
String host = "localhost";
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
//creating message to send from standard input
String newmessage = "";
try
{
// input the message from standard input
BufferedReader input= new BufferedReader(new InputStreamReader(System.in));
String line = "";
line= input.readLine();
newmessage += line + " ";
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
String sendMessage = newmessage;
bw.write(sendMessage + "\n");
bw.flush();
System.out.println("Message sent to server: "+sendMessage);
runClientRead(args);
}
}
Thread ClientRead = new Thread();
public void runClientRead(String args[]) throws IOException
{
System.out.println("Client recieve/read thread is now running");
//Integer port= Integer.valueOf(args[0]);
//String host = "localhost";
//InetAddress address = InetAddress.getByName(host);
//socket = new Socket(address, port);
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String MessageFromServer = br.readLine();
System.out.println("Message received from server: " + MessageFromServer);
}
}
Code of main function file (DirectMessengerCombined):
import java.io.IOException;
public class DirectMessengerCombined
{
public static void main(String[] args) throws IOException
{
DirectMessengerClient client1 = null;
DirectMessengerServer server1 = null;
for (int i = 0; i < args.length; i++)
{
if (args.length == 1)
{
client1 = new DirectMessengerClient(args);
client1.ClientRun(args);
}
else if (args.length == 2)
{
server1 = new DirectMessengerServer(args);
server1.ServerRun(args);
}
i=args.length + 20;
}
}
}
My question is: Why is the server able to accept the first message but not able to accept the second message ("how are you")?

Handle more clients

Right now my server only can handle one client at a time. I am trying to use a Thread so that the server can handle several clients, but I am doing it wrong. I have added the thread in the try/catch clause where the serverSocket accepts the client, but this makes no difference. I don't get an error or anything, but it just doesn't work.
So what I want to do, is make the server not freeze at one client, but still accept several clients.
Here is the server code:
import java.io.*;
import java.net.*;
public class Server {
private BufferedReader reader;
private PrintWriter writer;
private int port;
public Server(int port)
{
this.port = port;
}
private String getSeverAddress() {
String host = null;
try {
InetAddress adr = InetAddress.getLocalHost();
host = adr.getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return host;
}
public void startServer() {
print("Contact this sever on address: " + getSeverAddress() + " port: " + port);
ServerSocket ss = null;
Socket socket = null;
Thread clientThread = null;
try {
ss = new ServerSocket(port);
socket = ss.accept();
clientThread = new Thread(new Client(socket));
clientThread.start();
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new PrintWriter(socket.getOutputStream(), true);
String msg = null;
while (( msg = reader.readLine()) != null) {
print("System out: " + msg);
if(msg.equals("Bye")) {
print("Client left");
break;
}
}
ss.close();
socket.close();
reader.close();
writer.close();
} catch(SocketException e) {
e.printStackTrace();
} catch (IOException i ) {
i.printStackTrace();
return;
}
}
private void print(String msg) {
System.out.println(msg);
}
public static void main(String[] args) {
Server server = new Server(1111);
server.startServer();
}
}
Here is the client code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Client implements Runnable{
private Socket client;
private BufferedReader reader;
private PrintWriter writer;
public Client(Socket socket)
{
client = socket;
try{
reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
writer = new PrintWriter(client.getOutputStream(), true);
} catch (Exception e) {
e.printStackTrace();
return;
}
}
#Override
public void run() {
String msg = null;
BufferedReader r = null;
try {
r = new BufferedReader(new InputStreamReader(System.in));
} catch (Exception e1) {
e1.printStackTrace();
}
System.out.println("Write message to server");
while(true) {
try {
msg = r.readLine();
if(msg.equals("Quit") || msg == null) {
print("Disconnect");
break;
}
} catch (IOException e) {
e.printStackTrace();
}
writeToServer(msg);
}
try {
r.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeToServer(String msg) {
writer.println(msg);
}
private void print(String msg) {
System.out.println(msg);
}
public static void main(String[] args) {
Socket socket = null;
try {
socket = new Socket("localhost", 1111);
} catch (Exception e) {
e.printStackTrace();
}
Client client = new Client(socket);
client.run();
}
}
You are still trying to handle clients in your main thread. Main thread should just accept new connections and start new threads. You also have to do accept in a loop so multiple connections can be accepted:
ss = new ServerSocket(port);
while(true) {
Socket socket = ss.accept();
Thread clientThread = new Thread(new Runnable() {
public void run() {
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
String msg = null;
while (( msg = reader.readLine()) != null) {
print("System out: " + msg);
if(msg.equals("Bye")) {
print("Client left");
break;
}
}
socket.close();
reader.close();
writer.close();
}});
clientThread.start();
}
You need to put your ss.accept() into a while loop and create a new Thread for every client accepted, which handles the connection.

br.readline() gets stuck while br.read() works

I am making a simple ftp client/server program which on command from the clients lists files, tells the current directory, downloads files
My client code works fine since i have already tested it with a working server. However the server that i have designed gets stuck in the run() function on the line String message = br.readline(); If instead i use the br.read(), then it works but i need command in form of a string to know which file i have to download whereas br.read() returns int. Here's my code, i have used threading.
public class Myserver {
static final int PortNumber = 108;
static ServerSocket MyService;
static Socket clientSocket = null;
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
File directory;
directory = new File(System.getProperty("user.home"));
try {
MyService = new ServerSocket(PortNumber);
String cd = directory.toString();
System.out.println(cd);
System.out.println("Listening on " + PortNumber);
while(true) {
clientSocket = MyService.accept();
Connecthandle a = new Connecthandle(clientSocket, directory);
a.run();
}
}
catch (IOException e) {
System.out.println(e);
}
}
static class Connecthandle extends Thread {
File Directory;
Socket clientsocket;
// Constructor for class
Connecthandle(Socket clients, File dir) {
clientsocket = clients;
Directory = dir;
}
// Works Fine
void listfiles() throws IOException {
String []Listfile = Directory.list();
String send = "";
for (int j = 0; j < Listfile.length; j++) {
send = send + Listfile[j] + ",";
}
DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream());
GoingOut.writeBytes(send);
GoingOut.flush();
GoingOut.close();
}
// Works Fine
void currentdirectory() throws IOException {
String cd = Directory.toString();
String cdd = "resp," + cd;
System.out.println(cdd);
DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream());
GoingOut.writeBytes(cdd);
GoingOut.flush();
GoingOut.close();
System.exit(0);
}
void sendfiles(String fileName) {
try {
File nfile = new File(fileName);
DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream());
if ( (! nfile.exists()) || nfile.isDirectory() ) {
GoingOut.writeBytes("file not present");
} else {
BufferedReader br = new BufferedReader(new FileReader(nfile));
String line;
while ((line = br.readLine()) != null) {
line = br.readLine();
GoingOut.writeBytes(line+"\n");
}
GoingOut.flush();
GoingOut.close();
br.close();
}
} catch (IOException e) {
System.out.println("Unable to send!");
}
}
#SuppressWarnings("deprecation")
public void run() {
try {
DataInputStream comingin = new DataInputStream(clientsocket.getInputStream());
InputStreamReader isr = new InputStreamReader(comingin, "UTF-8");
BufferedReader br = new BufferedReader(isr);
System.out.println("here");
// if (br.ready())
String message = br.readLine(); // Code gets stuck here, if i use br.read() it works, but i need string output.
if (message.equals("listfiles\n")) {
listfiles();
} else if (message.equals("pwd")) {
currentdirectory();
} else if (message.contains("getfile,")) {
String fileName = new String(message.substring(8, message.length()));
sendfiles(fileName);
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
clientsocket.close();
} catch (IOException e) {}
}
}
}
}
If readLine() is blocking and you are sending data, you aren't sending a newline.

java.net.SocketException: Connection Reset

I'm trying to write a socket program where a string is sent to the server, reversed and the reversed string is sent back to the client.
Here's my server code:
import java.io.*;
import java.net.*;
class ClientSystem
{
public static void main(String[] args)
{
String hostname = "127.0.0.1";
int port = 1234;
Socket clientsocket = null;
DataOutputStream output =null;
BufferedReader input = null;
try
{
clientsocket = new Socket(hostname,port);
output = new DataOutputStream(clientsocket.getOutputStream());
input = new BufferedReader(new InputStreamReader(clientsocket.getInputStream()));
}
catch(Exception e)
{
System.out.println("Error occured"+e);
}
try
{
while(true)
{
System.out.println("Enter input string ('exit' to terminate connection): ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String inputstring = br.readLine();
output.writeBytes(inputstring+"\n");
//int n = Integer.parseInt(inputstring);
if(inputstring.equals("exit"))
break;
String response = input.readLine();
System.out.println("Reversed string is: "+response);
}
output.close();
input.close();
clientsocket.close();
}
catch(Exception e)
{
System.out.println("Error occured."+e);
}
/*finally
{
output.close();
input.close();
clientsocket.close();
}*/
}
}
Here's my server code:
import java.io.*;
import java.net.*;
public class ServerSystem
{
ServerSocket server = null;
Socket clientsocket = null;
int numOfConnections = 0, port;
public ServerSystem(int port)
{
this.port = port;
}
public static void main(String[] args)
{
int port = 1234;
ServerSystem ss = new ServerSystem(port);
ss.startServer();
}
public void startServer()
{
try
{
server = new ServerSocket(port);
}
catch(Exception e)
{
System.out.println("Error occured."+e);
}
System.out.println("Server has started. Ready to accept connections.");
while(true)
{
try
{
clientsocket = server.accept();
numOfConnections++;
ServerConnection sc = new ServerConnection(clientsocket, numOfConnections, this);
new Thread(sc).start();
}
catch(Exception e)
{
System.out.println("Error occured."+e);
}
}
}
public void stopServer()
{
System.out.println("Terminating connection");
System.exit(0);
}
}
class ServerConnection extends Thread
{
BufferedReader br;
PrintStream ps;
Socket clientsocket;
int id;
ServerSystem ss;
public ServerConnection(Socket clientsocket, int numOfConnections, ServerSystem ss)
{
this.clientsocket = clientsocket;
id = numOfConnections;
this.ss = ss;
System.out.println("Connection "+id+" established with "+clientsocket);
try
{
br = new BufferedReader(new InputStreamReader(clientsocket.getInputStream()));
ps = new PrintStream(clientsocket.getOutputStream());
}
catch(Exception e)
{
System.out.println("Error occured."+e);
}
}
public void run()
{
String line;
try
{
boolean stopserver = false;
while(true)
{
line = br.readLine();
System.out.println("Received string: "+line+" from connection "+id);
long threadID = Thread.currentThread().getId();
System.out.println("Thread ID: "+threadID+" is doing the current task.");
if(line.equals("exit"))
{
stopserver = true;
break;
}
else
{
int len = line.length();
String reversedstring = "";
for (int i=len-1; i>=0; i--)
reversedstring = reversedstring + line.charAt(i);
ps.println(""+reversedstring);
}
}
System.out.println("Connection "+id+" is closed.");
br.close();
ps.close();
clientsocket.close();
if(stopserver)
ss.stopServer();
}
catch(Exception e)
{
System.out.println("Error occured."+e);
}
}
}
I'm trying to open two clients. When I type "exit" in one of the clients (say client1), the server itself is terminating. But I don't want the server to close but just the connection to client1 to close. When I next type a string in client2, I get "java.net.SocketException: Connection Reset" .
How do I get rid of the exception and the connection at server be still open for client2?
It's your code:
while(true){
...
if(line.equals("exit"))
{
stopserver = true;
break;
}
...
}
...
if(stopserver)
ss.stopServer();

BufferedReader from server does not work

In this code I can correctly receive a request using BufferedReader inClient, created on the client socket.
Then I send the request to the server and I see the server gets it.
But then, when I try to read the reply from the server (using BufferedReader inServer on the socket of the server), it always ends in IOException: Impossible read from server.
I am referring to the block ################
Do you know any possible reasons?
import java.io.*;
import java.net.Socket;
import java.net.ServerSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class ProxyMain {
public static void main(String argv[]) {
int proxyPort = 55554;
String proxyAddr = "127.0.0.1";
ServerSocket proxySocket = null;
try {
proxySocket = new ServerSocket(proxyPort, 50, InetAddress.getByName("127.0.0.1"));
}
catch (Exception e) {
System.err.println("Impossible to create socket server!");
System.out.flush();
System.exit(1);
}
System.out.printf("Proxy active on port: %d and on address %s\n", proxyPort, proxySocket.getInetAddress());
System.out.println();
while (true) {
Socket client = null;
Socket sockServ = null;
BufferedReader inClient = null;
PrintWriter outClient = null;
BufferedReader inServer = null;
PrintWriter outServer = null;
String request = new String();
String tmp = new String();
String reply = new String();
String tmpReply = new String();
try {
client = proxySocket.accept();
System.out.println("Connected to: ");
System.out.println(client.getInetAddress().toString());
System.out.printf("On port %d\n", client.getPort());
System.out.println();
inClient = new BufferedReader(new InputStreamReader(client.getInputStream()));
outClient = new PrintWriter(client.getOutputStream(), true);
}
/*catch (IOException e) {
System.err.println("Couldn't get I/O for connection accepted");
System.exit(1);
}*/
catch (Exception e) {
System.out.println("Error occurred!");
System.exit(1);
}
System.out.println("Received request:");
try{
for (int i = 0; i<2; i++) {
tmp = inClient.readLine();
request = request + tmp;
}
inClient.close();
}
catch (IOException ioe) {
System.err.println("Impossible to read mhttp request!");
System.exit(1);
}
System.out.println(request);
System.out.println();
try {
sockServ = new Socket("127.0.0.1", 55555);
outServer = new PrintWriter(sockServ.getOutputStream(), true);
inServer = new BufferedReader(new InputStreamReader(sockServ.getInputStream()));
}
catch (UnknownHostException e) {
System.err.println("Don't know about host: 127.0.0.1:55555");
System.exit(1);
}
catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: 127.0.0.1:55555");
System.exit(1);
}
outServer.println(request);
outServer.close();
try {
#################################################
while ((tmpReply = inServer.readLine()) != null) {
System.out.println(tmpReply);
reply = reply + tmpReply;
}
inServer.close();
sockServ.close();
}
catch (IOException ioe) {
System.err.println("Impossible to read from server!");
System.exit(1);
}
outClient.println(reply);
outClient.close();
try {
client.close();
}
catch (IOException ioe) {
System.err.printf("Impossible to close connection with %s:%d\n", client.getInetAddress().toString(), client.getPort());
}
}
}
}
UPDATE:
It seems that if I do:
boolean res = inServer.ready();
it always return false.
So Server is not ready to send the reply but this is strange...with my Project in C e Python it worked immediately. Why should java be different?
When you close outServer, you close the underlying socket. if you just want to close the output and keep the input open, you need to use Socket.shutdownOutput(). note, you have the same problem when you close inClient.
This works, maybe you can get some ideas from it...
ChatServer - broadcasts to all connected clients
In one command prompt: java ChartServer
In another: java ChatClient localhost (or the ip address of where the server is running)
And another: java ChatClient localhost (or the ip address of where the server is running)
Start chatting in the client windows.
Server like this...
// xagyg wrote this, but you can copy it
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer {
public static List list = new ArrayList();
public static void main(String[] args) throws Exception {
ServerSocket svr = new ServerSocket(4444);
System.out.println("Chat Server started!");
while (true) {
try {
Socket s = svr.accept();
synchronized(list) {
list.add(s);
}
new Handler(s, list).start();
}
catch (IOException e) {
// print out the error, but continue!
System.err.println(e);
}
}
}
}
class Handler extends Thread {
private Socket s;
private String ipaddress;
private List list;
Handler (Socket s, List list) throws Exception {
this.s = s;
ipaddress = s.getInetAddress().toString();
this.list = list;
}
public void run () {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
String message;
//MyDialog x = (MyDialog)map.get(ipaddress.substring(1));
while ((message = reader.readLine()) != null) {
if (message.equals("quit")) {
synchronized(list) {
list.remove(s);
}
break;
}
synchronized(list) {
for (Object object: list) {
Socket socket = (Socket)object;
if (socket==s) continue;
PrintWriter writer = new PrintWriter(socket.getOutputStream());
writer.println(ipaddress + ": " + message);
writer.flush();
}
}
}
try { reader.close(); } catch (Exception e) {}
}
catch (Exception e) {
System.err.println(e);
}
}
}
Client like this ...
// xagyg wrote this, but you can copy it
import java.util.*;
import java.io.*;
import java.net.*;
public class ChatClient {
public static void main(String[] args) throws Exception {
Socket s = new Socket(args[0], 4444);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String message;
new SocketReader(in).start();
while ((message = reader.readLine())!=null) {
out.println(message);
out.flush();
if (message.equals("quit")) break;
}
in.close();
out.close();
}
}
class SocketReader extends Thread {
BufferedReader in;
public SocketReader(BufferedReader in) {
this.in = in;
}
public void run() {
String message;
try {
while ((message = in.readLine())!=null) {
System.out.println(message);
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
}

Categories