blocking IO method throw NoSuchException in while loop - Java - java

I am new to socket programming and not very familiar with I/O class.
In the following codes, I am making a simple socket program and use while loop to make it able to accept clientSocket for more than one time. The codes were executed well in the first iteration while throws NoSuchElementException when it reaches header = in.nextLine() (in the run method of the thread). I thought the method is blocking and should wait for the input? Similar things happen when I call next().
Can anyone help me understand this? I will greatly appreciate it!
public static void main(String args[]) throws IOException {
Socket clientSocket = null;
ServerSocket listenSocket = new ServerSocket(8888);
int num = 0;
try {
while (true) {
clientSocket = listenSocket.accept();
new ClientSocket(clientSocket, num++).start();
}
} finally {
listenSocket.close();
}
}
private static class ClientSocket extends Thread {
private Socket socket;
private int numOfSocket;
public ClientSocket(Socket s, int num) {
socket = s;
numOfSocket = num;
}
public void run() {
//get file location
String header;
String fileLocation = null;
Scanner in = null;
Scanner scanner = null;
PrintWriter out = null;
try {
// Get header && extract file location
in = new Scanner(socket.getInputStream());
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
header = in.nextLine();
System.out.println(header);
String[] headerArr = header.split(" ");
String url = headerArr[1];
fileLocation = url.substring(1);
System.out.println(fileLocation);
// Try to get the file
FileInputStream file = new FileInputStream(fileLocation);
System.out.println("file found");
out.println("HTTP/1.1 200 OK\n");
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
out.println(scanner.nextLine());
}
out.flush();
} catch (FileNotFoundException e) {
System.out.print("file not found");
out.println("HTTP/1.1 404 File not found\n");
try {
scanner = new Scanner(new File("fileNotFound.html"));
while (scanner.hasNextLine()) {
out.println(scanner.nextLine());
}
out.flush();
} catch (FileNotFoundException a) {
System.out.println(a.getMessage());
}
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
in.close();
out.close();
if (scanner != null) {
scanner.close();
}
try {
socket.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
}
More Clarifications:
So I ran it in Netbeans IDE and used a Chrome browser as a client to test it. It worked well in the first few attempts and then started to throw exceptions. The client is not affected and can still get the correct response. Just the server side is affected. Here is the message from the console.
Blockquote
GET /hah HTTP/1.1
hah
file not foundGET /favicon.ico HTTP/1.1
favicon.ico
file not foundGET /test.html HTTP/1.1
test.html
file found
Exception in thread "Thread-3" Exception in thread "Thread-5" Exception
in thread "Thread-4" java.util.NoSuchElementException: No line found
Blockquote

So eventually I figured out. It was the problem of the client(which was the Chrome browser)
When Chrome was visiting my server, it was actually sending 2 request. With one of my original request and the other is generated automatically to fetch meta data. Since my server is a simple and for educational purpose, it was not designed to handle errors not expected.
So the conclusion is that the codes works fine for its original purpose, but needs to be more robust in practical situations.

Related

Java - Getting error "Socket is closed" when my Client class connects on my Server class

I made two classes in Java named Server.java and Client.java. The Server is listening to a port and is waiting for a Client to connect (using sockets). When the client connects he can type a pair of numbers separated by "space" and if that pair exists in my edge_list.txt file the Server returns "1" to the client, if not it returns "0". After I completed my initial project I wanted to also use Threads so that it can handle multiple users at once, but when the Client connects I get -> java.net.SocketException: Socket is closed.
I reviewed my code and try using flush() instead of close(). Also, I thought I was closing the socket before the user can read the file, but it didn't seem that was the case. Below I will have the Server.java code block and not the Client.java, cause it doesn't seem to be the problem.
Server.java
import java.io.*;
import java.net.*;
import java.util.*;
public class Server {
private static final int PORT = 9999;
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
System.out.println("Server is listening on port " + PORT);
while (true) {
try (Socket socket = serverSocket.accept()) {
System.out.println("Client connected: " + socket);
new ClientHandler(socket).start();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static class ClientHandler extends Thread {
private Socket socket;
ClientHandler(Socket socket){
this.socket = socket;
}
#Override
public void run() {
try {
//Creating Sockets and Streams
InputStream input = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
OutputStream output = socket.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output));
while (socket.isConnected() && !socket.isClosed()) {
//Reading what the Client types
String request = reader.readLine();
//Split the values with "space" and store them in an array,
//then parse those values to two integers
String[] values = request.split(" ");
int A = Integer.parseInt(values[0]);
int B = Integer.parseInt(values[1]);
//Check if the pair in the file exists using checkPairInFile() method
boolean exists = checkPairInFile(A, B);
//if it does print 1 else 0
writer.println(exists ? "1" : "0");
//Flush the output to send the response back to the client
writer.flush();
}
//Print the disconnected user
System.out.println("Client disconnected: " + socket);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static boolean checkPairInFile(int A, int B) {
try (Scanner scanner = new Scanner(new File("edge_list.txt"))) {
//Scanning the file lines
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
//Split the values with "space"
String[] values = line.split(" ");
//Parse the values from String -> Int
int a = Integer.parseInt(values[0]);
int b = Integer.parseInt(values[1]);
//if both exist return true
if (A == a && B == b) {
return true;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return false;
}
}
P.S. Thanks in advance for your help, in case this is problem with my Client.java file I will update the post.
This part:
try (Socket socket = serverSocket.accept()) {
System.out.println("Client connected: " + socket);
new ClientHandler(socket).start();
}
accepts a socket, then prints a message, then starts a new thread, then closes the socket. At some point later the new thread finishes starting up and tries to use the socket and realizes it was already closed.
try (...) {...} (officially called try-with-resources) always closes the things when it gets to the }. That's the point of it. If you don't want to close the socket at the } then you shouldn't use this type of statement.

Java Socket program to read back from the server

I am trying to implement a simple java server and client - where client sends "hey" and server sends "hello" back. The problem I am having is even though the server sees hey but client never receives hello.
Here is the server code
try {
InputStream input = clientSocket.getInputStream();
System.out.println("client's request"+ IOUtils.toString(input));
OutputStream output = clientSocket.getOutputStream();
PrintWriter pw = new PrintWriter(output);
pw.write("hello");
pw.flush();
/*BufferedOutputStream bf = new BufferedOutputStream(output);
bf.write("hello".getBytes());*/
/*output.write(("hello").getBytes());*/
long time = System.currentTimeMillis();
System.out.println("Request processed: " + time);
}
catch (IOException e)
{
// report exception somewhere.
e.printStackTrace();
}
Client program
Socket s = new Socket("localhost",9000);
OutputStream out = s.getOutputStream();
out.write("hey".getBytes());
/*PrintWriter pw = new PrintWriter(out);
pw.write("hey");
pw.flush(); */
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String line;
while((line =br.readLine())!= null)
{
System.out.println(line);
}
s.close();
I have different variations of reading and writing the input/output but with no luck. Suggestions please.
Thanks
This won't work. IOUtils.toString(input) will read from the input until end of stream, which won't occur until the peer closes the connection, which won't occur at all because he is blocked in readLine() trying to read the response to the request that you are blocked forever reading.
Use BufferedReader.readLine(), but without the loop you have in the client.
This
void writeLine(BufferedWriter writer, String text) throws IOException {
writer.write(text); // the actual characters we want to send
writer.newLine(); // something that signals the end of the message.
writer.flush(); // and we must enforce that these bytes are sent and not buffered locally.
}
can be read by
String readLine(BufferedReader reader) throws IOException {
// reads characters until it finds either a newline or end of stream
// returns data or null when the stream has already ended
return reader.readLine();
}
When you send messages over sockets you must make sure that you have some kind of "protocol" to delimit your messages. For example by sending a newline after each message. That way both sides know where messages in a continuous stream of data ends.
Besides sending the right kind message, you also have to make sure to actually send it. BufferedWriter for example has a data-buffer and will not send data until the buffer is full enough. This will in most cases mean that messages will remain in the buffer instead of being sent over the wire. To do that call flush() once you have written everything you need.
I have different variations of reading and writing the input/output but with no luck.
In your case you don't send a newline but wait for it via readLine. The client should have actually received the "hello" part but it's not going to return from readLine without newline/end of stream (which should happen if you stop the server at this point). The same should apply to the message you send to your server but I guess you do kill the client at this point and therefore see the message.
Here is also the code I made while playing around with this
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.CountDownLatch;
class Hello {
static int port = 12345;
private static void writeLine(BufferedWriter writer, String line) throws IOException {
System.out.println(">> " + line);
writer.write(line); // the actual characters that we want to send
writer.newLine(); // something that signals the end of the message.
writer.flush(); // and we must enforce that these bytes are sent and not buffered locally.
}
private static String readLine(BufferedReader reader) throws IOException {
// reads characters until it finds either a newline or the end of the stream
// returns data or null when the stream has already ended
return reader.readLine();
}
static void handle(Socket cs, boolean controlling) {
try (Socket socket = cs) {
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
if (controlling) {
writeLine(writer, "hey");
}
loop: while (!Thread.currentThread().isInterrupted()) {
String readLine = readLine(reader);
System.out.println("<< " + readLine);
if (readLine == null)
break;
switch (readLine) {
case "hey":
writeLine(writer, "ho");
break;
case "ho":
writeLine(writer, "bye");
break;
case "bye":
break loop;
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
static void server(CountDownLatch latch) {
try (ServerSocket ss = new ServerSocket(port)) {
System.out.println("Listening.");
latch.countDown();
while (!Thread.currentThread().isInterrupted()) {
Socket clientSocket = ss.accept();
// spawn a new thread per client
new Thread(() -> handle(clientSocket, false)).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
static void client() {
System.out.println("Connecting.");
try (Socket socket = new Socket("localhost", port)) {
System.out.println("Connected.");
handle(socket, true);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
new Thread(() -> server(latch)).start();
latch.await();
new Thread(() -> client()).start();
}
}

java.lang.NullPointerException and java.net.SocketException

I’m trying to socket program in Java. Here the client sends a string which should be reversed by the server and sent back to the client. The server is a multithreaded server. Here is the client-side 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);
}
}
}
Here is the server side 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, reversedstring = "";
try
{
boolean stopserver = false;
while(true)
{
line = br.readLine();
System.out.println("Received string: "+line+" from connection "+id);
//long n = Long.parseLong(line.trim());
if(line.equals("exit"))
{
stopserver = true;
break;
}
else
{
int len = line.length();
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 get a java.lang.NullPointerException on the server side code when I enter the string and when i try to re-enter the string I get a java.net.SocketException: Socket closed exception.
Client side output:
Enter input string ('exit' to terminate connection):
usa
Reversed string is: asu
Enter input string ('exit' to terminate connection):
usa
Error occured.java.net.SocketException: Socket closed
Server side output:
Server has started. Ready to accept connections.
Connection 1 established with Socket[addr=/127.0.0.1,port=3272,localport=1234]
Received string: usa from connection 1
Received string: null from connection 1
Error occured.java.lang.NullPointerException
I tried a lot but I don't get from where I get these exceptions.
These 3 lines are the culprits in the client code:
output.close();
input.close();
clientsocket.close();
Put them outside of the while loop, and in the finally block:
try {
while(true) {
// client code here
}
} catch (Exception e) {
e.printStackTrace(); // notice this line. Will save you a lot of time!
} finally {
output.close(); //close resources here!
input.close();
clientsocket.close();
}
The issue is that as it was originally, you closed every resource, but in the next iteration, you wanted to use them agai, without initialising them...
Sidenote
Properly handling exceptions including proper logging of them. Always use either a logging framework like log4j
LOG.error("Unexpected error when deionizing the flux capacitor",e);
, or the printStackTrace() method
e.printStackTrace();
And don't forget to include the line numbers in your code, if you post a stacktrace....
EDIT
For the reversed issue:
else
{
int len = line.length();
reversedString=""; //this line erases the previous content of the reversed string
for (int i=len-1; i>=0; i--) { //always use brackets!!!
reversedstring = reversedstring + line.charAt(i);
}
ps.println(""+reversedstring);
}
What happened? The reversedString just grew and grew with each iteration, without getting erased... This is why I like to declare my variables in just the most strict scope I need them.
EDIT
To make the exit command no tkill the server, this can be one (very simple) solution:
In the ServerConnection class:
while(true)
{
line = br.readLine();
System.out.println("Received string: "+line+" from connection "+id);
if(line.equals("exit"))
{
break; //just stop this connection, don't kill server
}
else if(line.equals("stop"))
{
stopserver = true; //stop server too
break;
}
else
{
int len = line.length();
for (int i=len-1; i>=0; i--) {
reversedstring = reversedstring + line.charAt(i);
}
ps.println(""+reversedstring);
}
}
What is happening here? There is a new "command" stop, which makes the server stop, and the exit just exits the client, but does not stop the server itself...
in the 1st run of the loop you are closing all the connections which is causing the issue.
output.close();
input.close();
clientsocket.close();,move it down
Your server is calling br.readLine(); It will wait until the client sends it, but once you send a String you call:
output.close();
input.close();
clientsocket.close();
That will release the resource and result in br.readLine() being null
if (line.equals("exit")) { Here line is null, therefore you cannot call equals.
if ("exit".equals(line)) { You can change it like this to prevent that exception here.
Move the close statements to a finally block, even in the server should, if you have an exception in the while, the close are never reached, that may cause memory leaks.
Client:
} finally {
output.close();
input.close();
clientsocket.close();
}
Server:
} finally {
br.close();
ps.close();
clientsocket.close();
}
Note: you can validate them before closing to ensure they are not null.
You may have to provide a case for the input being null anyway, either exit the loop, usually you would use something like this:
if (null==line || "exit".equals(line)) {
If the client sends a null, something is wrong.

Web browser command line program

I am working on a web server (done), and thought I would make my own little text-based browser, the only problem is that I can't actually get the browser to read the responses. Here is the code:
import java.io.*;
import java.net.*;
class client
{
static Socket socket = null;
static BufferedReader in = null;
static PrintWriter out = null;
public static void main(String args[])
{
int fromServer;
try
{
socket = new Socket("localhost", 8001);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter( new BufferedOutputStream(socket.getOutputStream()));
out.println("GET /Library/WebServer/Documents/index.html.en HTTP/1.0");
out.flush();
while ((fromServer = in.read()) != -1)
{
System.out.write(fromServer);
System.out.flush();
}
}
catch (UnknownHostException e)
{
System.out.println("Unknown host");
}
catch (IOException e)
{
System.out.println("IO error");
}
}
}
You haven't completely finished the request. You need two newlines, as otherwise it just looks like you're still writing out the request headers.
Add an extra println and you may be okay, although as HTTP specifies CRLF for the line ending, I would actually use print rather than println, and put \r\n at the end of each line explicitly.
(I'd also avoid using PrintWriter, personally - swallowing exceptions is bad...)

Socket data does not appear to be getting through to client

I've written some serverside socket handling code and I'm concerned that potentially my packets are not always making it back to the client. I am logging all my events and in my log files it says I am sending the information. But the client is also logging events and in their logs they say they do not receive anything.
My code to send the data is as follows:
public void write(Packet packet) {
String data = packet.serialize();
log("Send=[" + data + "]", "Write"); // log to file
try {
_writer.write(data);
_writer.flush();
} catch (Exception ex) {
log(ex, "write");
}
}
Each socket is created on a new thread and I create my writers and readers immediately like so (in the public run method):
// _sockt is a Java Socket object
_writer = new BufferedWriter(new OutputStreamWriter(_socket
.getOutputStream()));
_reader = new SocketReader(_socket);
SocketReader is just a wrapper class I created for listening for responses and has a public read method like so:
public String read() throws IOException, SocketTimeoutException {
_socket.setSoTimeout(_timeOut);
if(_reader == null)
_reader = new BufferedReader(new InputStreamReader(_socket.getInputStream()));
// read from the stream
return new PacketDataInputStream(_reader).read();
}
The PacketDataInputStream wrapper class:
BufferedReader _reader = null;
public PacketDataInputStream(BufferedReader reader)
{
_reader = reader;
}
public String read() throws IOException, SocketException {
StringBuilder builder = new StringBuilder();
int c = 0;
while((c = _reader.read()) != -1)
{
char ch = (char)c;
builder.append(ch);
if(ch == PacketConstants.ETX)
break;
}
if(builder.length() > 0)
return builder.toString();
else
return null;
}
The way I'm creating the actual socket listener objects is pretty standard I think:
InetAddress address = InetAddress.getByName(IP);
server = new ServerSocket( port, 0, address);
// My own manager class to handle all the sockets connected
WebSocketManager manager = new WebSocketManager(this);
Socket connection = null;
while(bContinue)
{
connection = server.accept();
if(bContinue) {
// assign the socket to a new thread and start
// that thread
manager.newSocket(connection);
} else {
connection.close();
}
}
Is is possible that I'm using the wrong objects for sending the data back.
Should I even be using a bufferedwriter and reader? I had thought that these were the best way to go but now I'm not so sure.
It's important to note that this does not happen all the time, just sporadically. It could be the clients code having bugs but I need to make sure that I'm doing it correctly before going back to them.
This code is run on a Linux Ubuntu server. Logging occurs to a text file, nothing special there. My log files show the Send="" data going back to the client and no exception so it appears as if the .write and .flush() worked? Socket connections are persistant and only closed by the client and or network issues.
UPDATE ----- Client Side code -------:
I did manage to get some of the client side code for how they are handling the send and receiving of data (just in case it's more obvious on their end). The client is actually connecting to this server via an Android device (if that helps).
Creation of socket
static final int BUFFER_SIZE = 20000; // Maximum packet size
java.net.InetAddress server = java.net.InetAddress.getByName(url);
socket = new Socket(server, port);
// Set socket options:
socket.setReceiveBufferSize(BUFFER_SIZE);
socket.setSendBufferSize(BUFFER_SIZE);
socket.setKeepAlive(true);
socket.setTcpNoDelay(true);
Sending:
try {
// Send the packet:
OutputStream stream = socket.getOutputStream();
stream.write(p.getByteArray ());
stream.flush();
// Update the time:
lastPacketSendTime = new Date ();
} catch (IOException e) {
setError("Error sending packet (" + e.getMessage() + ")", ERROR_IO);
return false;
}
Receiving:
socket.setSoTimeout(timeout);
// Get the reader:
inputStream = socket.getInputStream();
while (true) {
// Get the next character:
int value = inputStream.read();
// Check for -1, indicating that the socket is closed:
if (value == -1) {
// The socket is closed remotely, so close it locally as well:
disconnect();
inputStream = null;
return null;
}
// ... and a bunch of other stuff to handle the actual data
}
EDIT 14-Nov:
This is actually proving to be more of a problem now. Both the client logs and the server logs appear to be sending. But at times the data doesn't appear to come through or if it does it is sometimes coming through 10 - 30 - 60 second delayed.
I can provide more information if required.
When you use BufferedReaders and BufferedWriters things get buffered. How about using the input and output streams directly.. Also, writers are character based, I don't know if you need to send binary data but if so that will be a problem with writers.
I am not sure whether this will be to your any use or not.. but i am giving you the code i used for client server communication..
Client Side:
public class ClientWala {
public static void main(String[] args) throws Exception{
Boolean b = true;
Socket s = new Socket("127.0.0.1", 4444);
System.out.println("connected: "+s.isConnected());
OutputStream output = s.getOutputStream();
PrintWriter pw = new PrintWriter(output,true);
// to write data to server
while(b){
if (!b){
System.exit(0);
}
else {
pw.write(new Scanner(System.in).nextLine());
}
}
// to read data from server
InputStream input = s.getInputStream();
InputStreamReader isr = new InputStreamReader(input);
BufferedReader br = new BufferedReader(isr);
String data = null;
while ((data = br.readLine())!=null){
// Print it using sysout, or do whatever you want with the incoming data from server
}
}
}
Server Code:
import java.io.*
import java.net.*;
public class ServerTest {
ServerSocket s;
public void go() {
try {
s = new ServerSocket(44457);
while (true) {
Socket incoming = s.accept();
Thread t = new Thread(new MyCon(incoming));
t.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
class MyCon implements Runnable {
Socket incoming;
public MyCon(Socket incoming) {
this.incoming = incoming;
}
#Override
public void run() {
try {
PrintWriter pw = new PrintWriter(incoming.getOutputStream(),
true);
InputStreamReader isr = new InputStreamReader(
incoming.getInputStream());
BufferedReader br = new BufferedReader(isr);
String inp = null;
boolean isDone = true;
System.out.println("TYPE : BYE");
System.out.println();
while (isDone && ((inp = br.readLine()) != null)) {
System.out.println(inp);
if (inp.trim().equals("BYE")) {
System.out
.println("THANKS FOR CONNECTING...Bye for now");
isDone = false;
s.close();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
try {
s.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new ServerTest().go();
}
}

Categories

Resources