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();
Related
I have a server and client. My problem is that when the client writes messages, the server is not receiving the messages.
Server code
public class BankServer {
private int port;
private BufferedReader reader = null;
private PrintWriter writer = null;
public BankServer(int port)
{
this.port = port;
}
public void startServer() {
print("Contact server at: " + getServerAddress() + ": port: " + port);
while(true) {
try {
ServerSocket ss = new ServerSocket(port);
Socket client = ss.accept();
if(client != null) {
print("Client connected");
}
reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
writer = new PrintWriter(client.getOutputStream(), true);
String msg = null;
print("Server waiting for input");
while((msg = reader.readLine()) != null) {
print("Printer: " + msg);
writer.write(msg);
}
client.close();
ss.close();
closeStreams();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void closeStreams() {
if(reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
} }
if(writer != null) {
writer.close();
}
}
private String getServerAddress() {
InetAddress inetAdr = null;
try {
inetAdr = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
String host = inetAdr.getHostAddress();
return host;
}
public void print(String msg) {
System.out.println(msg);
}
public static void main(String[] args) {
new BankServer(2222).startServer();
}
}
I have this code, where the Server waits for input:
ServerSocket ss = new ServerSocket(port);
Socket client = ss.accept();
if(client != null) {
print("Client connected");
}
From this code, I can see that a connection is made. But when client sends messages, they are not printed by the server
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;
import java.util.Scanner;
public class BankClient {
private PrintWriter writer = null;
private BufferedReader reader = null;
private Socket socket;
private int port;
private String adr;
public BankClient(String address, int port)
{
adr = address;
this.port = port;
try {
socket = new Socket(adr, this.port);
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new PrintWriter(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeMsg(String msg) {
try {
while((msg = reader.readLine()) != null) {
writer.print("From client: " + msg);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
BankClient client = new BankClient("127.0.0.1", 2222);
Scanner scanner = new Scanner(System.in);
System.out.println("Waiting for input");
while(true) {
String msg = scanner.nextLine();
client.writeMsg(msg);
if(msg.equals("quit")) {
System.out.println("Bye");
break;
}
}
scanner.close();
}
}
This is the first time I work with streams, and I am also pretty new to programming. I have found a lot of help on stackoverflow, and google, but I just can't figure this out.
Thanks for any help you can provide
Replace :
public void writeMsg(String msg) {
try {
while((msg = reader.readLine()) != null) {
writer.print("From client: " + msg);
}
} catch (IOException e) {
e.printStackTrace();
}
}
By :
public void writeMsg(String msg) {
try {
DataOutputStream outToServer = new DataOutputStream(socket.getOutputStream());
outToServer.writeBytes("From client: " + msg + "\n");
} catch (IOException e) {
e.printStackTrace();
}
}
Client Side:
Server Side :
Change
writer.print("From client: " + msg);
to
writer.println("From client: " + msg);
and remove the while((msg = reader.readLine()) != null) at the client.
EDIT: And you have to add writer.flush();. That worked for me.
EDIT2: The complete solution. Change BankClient here:
public void writeMsg(String msg) {
writer.println("From client: " + msg);
writer.flush();
}
I am trying to implement multi threading with a client/server program I have been working on. I need to allow multiple clients to connect to the server at the same time. I currently have 4 classes: a Client, a Server, a Protocol and a Worker to handle the threads. The following code is what I have for those classes:
SocketServer Class:
public class SocketServer {
public static void main(String[] args) throws IOException {
int portNumber = 9987;
try (
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
) {
Thread thread = new Thread(new ClientWorker(clientSocket));
thread.start(); //start thread
String inputLine, outputLine;
// Initiate conversation with client
Protocol prot = new Protocol();
outputLine = prot.processInput(null);
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
outputLine = prot.processInput(inputLine);
out.println(outputLine);
if (outputLine.equals("quit"))
break;
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
}
}
SocketClient Class:
public class SocketClient {
public static void main(String[] args) throws IOException
{
String hostName = "localhost";
int portNumber = 9987;
try (
Socket socket = new Socket(hostName, portNumber);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
) {
BufferedReader stdIn =
new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser;
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("quit"))
break;
fromUser = stdIn.readLine();
if (fromUser != null) {
System.out.println("Client: " + fromUser);
out.println(fromUser);
}
}
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
hostName);
System.exit(1);
}
}
}
Protocol Class:
public class Protocol {
private static final int waiting = 0;
private static final int sentPrompt = 1;
private int status = waiting;
public String processInput(String theInput) {
String theOutput = null;
if (status == waiting) {
theOutput = "Please enter what you would like to retrieve: 'customer' or 'product' ";
status = sentPrompt;
}
else if ( status == sentPrompt ) {
if ( theInput.equalsIgnoreCase("product")) {
File f = new File("product.txt");
Scanner sc = null;
try {
sc = new Scanner(f);
} catch (FileNotFoundException ex) {
Logger.getLogger(Protocol.class.getName()).log(Level.SEVERE, null, ex);
}
while ( sc.hasNextLine() ) {
String line = sc.nextLine();
theOutput = "The current product entries are : " + line;
}
return theOutput;
}
else if ( theInput.equalsIgnoreCase("customer")) {
File f = new File("customer.txt");
Scanner sc = null;
try {
sc = new Scanner(f);
} catch (FileNotFoundException ex) {
Logger.getLogger(Protocol.class.getName()).log(Level.SEVERE, null, ex);
}
while ( sc.hasNextLine() ) {
String line = sc.nextLine();
theOutput = "The current customer entries are : " + line;
}
return theOutput;
}
else if ( theInput.equalsIgnoreCase("quit")) {
return "quit";
}
else {
return "quit";
}
}
return theOutput;
}
}
The ClientWorker Class:
public class ClientWorker implements Runnable {
private final Socket client;
public ClientWorker( Socket client ) {
this.client = client;
}
#Override
public void run() {
String line;
BufferedReader in = null;
PrintWriter out = null;
try {
System.out.println("Thread started with name:"+Thread.currentThread().getName());
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintWriter(client.getOutputStream(), true);
} catch (IOException e) {
System.out.println("in or out failed");
System.exit(-1);
}
while (true) {
try {
System.out.println("Thread running with name:"+Thread.currentThread().getName());
line = in.readLine();
//Send data back to client
out.println(line);
//Append data to text area
} catch (IOException e) {
System.out.println("Read failed");
System.exit(-1);
}
}
}
}
When I run the server and client, everything works fine as expected. Then when I try to run another client, it just hangs there and does not prompt the client to give a response. Any insight into what I am missing is greatly appreciated!
Your server code should address implement below functionalities.
Keep accepting socket from ServerSocket in a while loop
Create new thread after accept() call by passing client socket i.e Socket
Do IO processing in client socket thread e.g ClientWorker in your case.
Have a look at this article
Your code should be
ServerSocket serverSocket = new ServerSocket(portNumber);
while(true){
try{
Socket clientSocket = serverSocket.accept();
Thread thread = new ClientWorker(clientSocket);
thread.start(); //start thread
}catch(Exception err){
err.printStackTrace();
}
}
How many times does serverSocket.accept() get called?
Once.
That's how many clients it will handle.
Subsequent clients trying to contact will not have anybody listening to receive them.
To handle more clients, you need to call serverSocket.accept() in a loop.
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.
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);
}
}
}
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.