SocketException thrown when stopping my TCP Server java - java

Im getting this error when closing my TCP Server from my form.
java.net.SocketException: Socket closed
at java.net.PlainSocketImpl.socketAccept(Native Method)
at java.net.AbstractPlainSocketImpl.accept(AbstractPlainSocketImpl.java:404)
at java.net.ServerSocket.implAccept(ServerSocket.java:545)
at java.net.ServerSocket.accept(ServerSocket.java:513)
at com.hightekjonathan.HomeServer.Server.Start(Server.java:36)
at com.hightekjonathan.HomeServer.Form$2.run(Form.java:81)
at java.lang.Thread.run(Thread.java:745)
Heres the Server.java:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.*;
import java.util.Enumeration;
public class Server {
private static ServerSocket serverSocket = null;
private static Socket socket = null;
private static DataInputStream dataInputStream = null;
private static DataOutputStream dataOutputStream = null;
private static int port = 19586;
private static boolean running = false;
public void Start() {
try {
System.out.println("Starting Server...");
serverSocket = new ServerSocket(port);
System.out.println("Server Started");
System.out.println("IP Address: " + getIpAddress());
System.out.println("Listening: " + serverSocket.getLocalPort());
running = true;
} catch (IOException e) {
e.printStackTrace();
}
try {
System.out.println("Attempting to connect to clients...");
socket = serverSocket.accept();
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
System.out.println("ip: " + socket.getInetAddress());
System.out.println("message: " + dataInputStream.readUTF());
dataOutputStream.writeUTF("connected");
} catch (Exception e) {
e.printStackTrace();
}
}
public void Stop() {
if (running) {
if (socket != null) {
try {
socket.close();
socket = null;
} catch (Exception e) {
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
running = false;
}
}
private String getIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ip += inetAddress.getHostAddress();
}
}
}
} catch (SocketException e) {
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
public boolean isRunning() {
return running;
}
}
Its started on a new thread from my GUI Form using this function:
button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonActionPerformed(evt);
}
);
And then buttonActionPerformed() is this:
private void buttonActionPerformed(java.awt.event.ActionEvent evt) {
if (!server.isRunning()) {
Runnable r = new Runnable() {
public void run() {
server.Start();
}
};
new Thread(r).start();
button.setText("Stop Server");
serverStatus.setText("Server: Started");
} else {
server.Stop();
button.setText("Start Server");
serverStatus.setText("Server: Stopped");
}
}
The error only appears when I stop the server when no clients have connected. But when a client connects, then disconnects, I don't get that error. It properly closes it, I just want to make sure that error won't be a serious problem, or if there is an easy way of fixing it.

When you start your server, you call serverSocket.accept(). This call blocks thread until a connection is made. And by calling server.stop() you are closing this server socket in another thread. ServerSocket.close() JavaDoc says:
Any thread currently blocked in {#link #accept()} will throw a {#link SocketException}.
So thats why you are getting this exception.
I think you can just ignore this exception.
P.S.
And you should make your boolean running volatile.

Related

Android client/server application - proper way to receive messages continously

I'm trying to make a client/server application using an Android phone as a client using AsyncTask to send messages from UI.
I've written some very basic implementation just to test the connection and the way that messages are received / sent and I found a very big problem.
The client part seems to work fine..from my perspective. But the server part is the problem. I can't make the server reading and displaying messages countinously from the client.
I tried something like while(line = (in.readLine()) != null) {} but it doesn't seems to work.
After I sent my first word from the client, the server reads null and it stops.
Can someone show me a proper way to keep the server running while the client is not sending nothing?
I'd like to avoid using while(true) if it's not 100% necessary.
Here is the implementation until now:
Server:
public class SocketServerThread extends Thread {
private static final Logger log = Logger.getLogger(SocketServerThread.class);
private static final int SERVER_PORT_NUMBER = 5000;
#Override
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(SERVER_PORT_NUMBER);
serverSocket.setReuseAddress(true);
log.info("Waiting for connection...");
Socket clientSocket = serverSocket.accept();
log.info("Connected! Receiving message...");
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
try {
while (true) {
String line = in.readLine();
if (line != null) {
log.info(line);
}
}
} catch (Exception e) {
log.error("Unexpected exception while sending / receiving messages.");
e.printStackTrace();
} finally {
in.close();
clientSocket.close();
serverSocket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
Client:
public class MyAsyncTask extends AsyncTask<String, Integer, String> {
private static final String TAG = "MyAsyncTask";
private static final String SERVER_IP_ADDRESS = "10.0.2.2";
private static final int SERVER_PORT_NUMBER = 5000;
private PrintWriter out;
#Override
protected String doInBackground(String... params) {
String message = "";
try {
InetAddress address = InetAddress.getByName(SERVER_IP_ADDRESS);
Log.d(TAG, "Connecting...");
Socket socket = new Socket(address, SERVER_PORT_NUMBER);
try {
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
Log.d(TAG, "I/O created");
message = params[0];
if (!message.equals("stop")) {
sendMessage(message);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
out.flush();
out.close();
socket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return message;
}
private void sendMessage(String message) {
if (out != null && !out.checkError()) {
out.println(message);
out.flush();
Log.d(TAG, "Sent message: " + message);
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d(TAG, "onPostExecute(), s: " + s);
}
Thank you.
The problem is that your BufferedReader only read the first input stream. In order to receive the text after that, you have to re-read the input stream. I do it by recreating the socket when I am done reading, so that I can read next coming data. I am using the following code in my app. You can use this
private ServerSocket serverSocket;
public static final int SERVERPORT = 5000;
Thread serverThread = null;
public void startSocketServer(){
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
}
public void stopSocket(){
if(serverSocket != null){
try{
serverSocket.close();
}
catch (IOException e){
e.printStackTrace();
}
}
}
class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
Log.wtf(TAG,"Socket: New Socket");
serverSocket = new ServerSocket(SERVERPORT);
if(serverSocket == null){
runOnUiThread(new Runnable() {
#Override
public void run() {
startSocketServer();
}
});
return;
}
while (!Thread.currentThread().isInterrupted() && !serverSocket.isClosed()) {
try {
socket = serverSocket.accept();
Log.wtf(TAG,"Socket: Accepting");
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (IOException e) {
Log.wtf(TAG,"Socket: Error");
e.printStackTrace();
}
if(Thread.currentThread().isInterrupted()){
Log.wtf(TAG, "Thread Interrupted");
}
if(serverSocket.isClosed()){
Log.wtf(TAG, "serverSocket closed");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class CommunicationThread implements Runnable {
private Socket clientSocket;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
log.info("Connected! Receiving message...");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
try {
while (true) {
String line = in.readLine();
if (line != null) {
log.info(line);
}
else
break;//This will exit the loop and refresh the socket for next data
}
} catch (Exception e) {
log.error("Unexpected exception while sending / receiving messages.");
e.printStackTrace();
}
finally {
in.close();
clientSocket.close();
}
refreshSocket();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void refreshSocket(){
runOnUiThread(new Runnable() {
#Override
public void run() {
stopSocket();
startSocketServer();
}
});
}
Just call startSocketServer() to start the server socket in your code.

"Stream closed" IOException in client-server application using java socket

my client breaks, because of "Stream closed" exception.
Server properly waits for connection, but client don't send any data because of "stream closed" Exception.
Server after waiting time echoes "Unexpected error".
Thanks for help!
My code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private static final int PORT = 50000;
static boolean flaga = true;
private static ServerSocket serverSocket;
private static Socket clientSocket;
public static void main(String[] args) throws IOException {
serverSocket = null;
try {
serverSocket = new ServerSocket(PORT);
} catch (IOException e) {
System.err.println("Could not listen on port: " + PORT);
System.exit(1);
}
System.out.print("Wating for connection...");
Thread t = new Thread(new Runnable() {
public void run() {
try {
while (flaga) {
System.out.print(".");
Thread.sleep(1000);
}
} catch (InterruptedException ie) {
//
}
System.out.println("\nClient connected on port " + PORT);
}
});
t.start();
clientSocket = null;
try {
clientSocket = serverSocket.accept();
flaga = false;
} catch (IOException e) {
System.err.println("Accept failed.");
t.interrupt();
System.exit(1);
}
final PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
final BufferedReader in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
t = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(5000);
while (true) {
out.println("Ping");
System.out.println(System.currentTimeMillis()
+ " Ping sent");
String input = in.readLine();
if (input.equals("Pong")) {
System.out.println(System.currentTimeMillis()
+ " Pong received");
} else {
System.out.println(System.currentTimeMillis()
+ " Wrong answer");
}
Thread.sleep(5000);
}
} catch (Exception e) {
System.err.println(System.currentTimeMillis()
+ " Unexpected Error");
}
}
});
t.start();
}
}
And 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 {
private static final int PORT = 50000;
private static final String HOST = "127.0.0.1";
public static void main(String[] args) throws IOException {
Socket socket = null;
try {
socket = new Socket(HOST, PORT);
} catch (Exception e) {
System.err.println("Could not connect to " + HOST + ":" + PORT);
System.exit(1);
}
final PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
final BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
Thread t = new Thread(new Runnable() {
public void run() {
long start = System.currentTimeMillis();
try {
while (true) {
try {
String input = in.readLine();
if (input != null) {
System.out.println(System.currentTimeMillis()
+ " Server: " + input);
}
if (input.equals("Ping")) {
if (System.currentTimeMillis() - start > 30000) {
out.println("Pon g");
System.out.println(System
.currentTimeMillis()
+ " Client: Pon g");
break;
}
out.println("Pong");
System.out.println(System.currentTimeMillis()
+ " Client: Pong");
} else {
System.out.println(start);
out.println("got");
}
} catch (IOException ioe) {
System.err.println(System.currentTimeMillis() + " "
+ ioe.getMessage());
ioe.getStackTrace();
System.exit(0);
}
}
} catch (Exception e) {
System.err.println(System.currentTimeMillis()
+ " Unexpected Error");
}
}
});
t.start();
out.close();
in.close();
socket.close();
}
}
In your client, you start the thread but directly close streams and socket:
t.start();
out.close();
in.close();
socket.close();
You can, as a test, move the stream and socket calls to the last catch block.
...
} catch (Exception e) {
System.err.println(System.currentTimeMillis()
+ " Unexpected Error");
out.close();
in.close();
socket.close();
}
}
});
t.start();
}

Java Client Server - Multiple Event Handling for the Client

I'm trying to setup a client server application using socket programming. My client connects to the server, but I'm unable to get the multiple event handling to work. My client applet has two text boxes and buttons associated with each one of of them. When I click button one, I was trying to get "Hello" to be displayed in the text box. When I click on button two, I was trying to get "Hello there" to be displayed in the second text box. However, only one value (the value I first click) shows up in both of the text boxes. Is my event handling mechanism incorrect? I am implementing the serializable interface and the client server communication deals with objects. Can someone please tell me what the problem in the code is? I haven't posted the ObjectCommunication.java code, but it simply implements the serializable interface and has the getter and setter (takes a string as an input parameter) method.
Many thanks!
The following is my server code:
import java.io.*;
import java.net.*;
public class Server_App {
public static void main(String[] args) {
try {
ServerSocket holder = new ServerSocket(4500);
for (;;) {
Socket incoming = holder.accept();
new ServerThread(incoming).start();
}
} catch (Exception e) {
System.out.println(e);
}
}
}
class ServerThread extends Thread
{
public ServerThread(Socket i) {
incoming = i;
}
public void run() {
try {
ObjectCommunication hold = new ObjectCommunication();
ObjectInputStream input = new ObjectInputStream(incoming.getInputStream());
ObjectOutputStream output = new ObjectOutputStream(incoming.getOutputStream());
hold = (ObjectCommunication) input.readObject();
if ((hold.getMessage()).equals("Event 1")) {
System.out.println("Message read: " + hold.getMessage());
hold.setMessage("Hello!");
} else if ((hold.getMessage()).equals("Event 2")) {
System.out.println("Message read:" + hold.getMessage());
hold.setMessage("Hello there!");
}
output.writeObject(hold);
input.close();
output.close();
incoming.close();
} catch (Exception e) {
System.out.println(e);
}
}
ObjectCommunication hold = null;
private Socket incoming;
}
The following is the client code:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class Client_App extends Applet {
TextField textVal;
TextField anotherTextVal;
Socket socket;
ObjectCommunication hold = new ObjectCommunication();
ObjectCommunication temp = new ObjectCommunication();
ObjectOutputStream OutputStream;
ObjectInputStream InputStream;
public void init() {
socketConnection();
createGUI();
validate();
}
public void socketConnection() {
try {
socket = new Socket("127.0.0.1", 4500);
} catch (Exception e) {
System.out.println("Unknown Host");
}
try {
OutputStream = new ObjectOutputStream(socket.getOutputStream());
InputStream = new ObjectInputStream(socket.getInputStream());
} catch (IOException ex) {
System.out.println("Error: " + ex);
return;
}
}
public void createGUI() {
Button button = new Button("Hello Button");
add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
button_actionPerformed(evt);
}
});
textVal = new TextField(6);
add(textVal);
Button anotherButton = new Button("Hello there Button");
add(anotherButton);
anotherButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
anotherButton_actionPerformed(evt);
}
});
anotherTextVal = new TextField(6);
add(anotherTextVal);
}
public void button_actionPerformed(ActionEvent e) {
String actionCommand = e.getActionCommand();
if (e.getSource() instanceof Button)
if (actionCommand.equals("Hello Button")) {
try {
temp.setMessage("Event 1");
//OutputStream.writeObject(temp);
new SendToServer().start();
new ListenToServer().start();
} catch (Exception ex) {
System.out.println("Communication didn't work!");
}
textVal.setText(hold.getMessage());
}
}
public void anotherButton_actionPerformed(ActionEvent evt) {
String action_Command = evt.getActionCommand();
if (evt.getSource() instanceof Button)
if (action_Command.equals("Hello there Button")) {
try {
temp.setMessage("Event 2");
new SendToServer().start();
new ListenToServer().start();
} catch (Exception ex) {
System.out.println("Communication didn't work!");
}
anotherTextVal.setText(hold.getMessage());
}
}
class ListenToServer extends Thread {
public void run() {
while (true) {
try {
hold = (ObjectCommunication) InputStream.readObject();
} catch (IOException e) {} catch (ClassNotFoundException e2) {}
}
}
}
class SendToServer extends Thread {
public void run() {
while (true) {
try {
OutputStream.writeObject(temp);
} catch (IOException e) {}
}
}
}
}
To be honest - I'm a little bit lazy to read through your code and seek there for a bug :) Nevertheless I'll post you here my snippet for socket-based multiple client-server application..
import java.net.*;
import java.io.*;
class ServeConnection extends Thread {
private Socket socket = null;
private BufferedReader in = null;
private PrintWriter out = null;
public ServeConnection(Socket s) throws IOException {
// init connection with client
socket = s;
try {
in = new BufferedReader(new InputStreamReader(
this.socket.getInputStream()));
out = new PrintWriter(this.socket.getOutputStream(), true);
} catch (IOException e) {
System.err.println("Couldn't get I/O.");
System.exit(1);
}
start();
}
public void run() {
System.out.println("client accepted from: " + socket.getInetAddress()
+ ":" + socket.getPort());
// get commands from client, until is he communicating or until no error
// occurs
String inputLine, outputLine;
try {
while ((inputLine = in.readLine()) != null) {
System.out.println("request: " + inputLine);
outputLine = inputLine;
out.println("I've recived "+outputLine);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("server ending");
out.close();
try {
in.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Server {
public static void svr_main(int port) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
System.err.println("Could not listen on port: " + port);
System.exit(1);
}
System.out.println("Server ready");
try {
while (true) {
Socket socket = serverSocket.accept();
try {
new ServeConnection(socket);
} catch (IOException e) {
System.err.println("IO Exception");
}
}
} finally {
serverSocket.close();
}
}
}
class Client {
static Socket echoSocket = null;
static PrintWriter out = null;
static BufferedReader in = null;
public static void cli_main(int port, String servername) throws
IOException {
try {
echoSocket = new Socket(servername, port);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + servername);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for " + servername);
System.exit(1);
}
System.out.println("Client ready!");
while (true) {
inputLine = (in.readLine().toString());
if (inputLine == null) {
System.out.println("Client closing!");
break;
}
// get the input and tokenize it
String[] tokens = inputLine.split(" ");
}
out.close();
in.close();
echoSocket.close();
System.out.println("Client closing");
}
}
public class MyClientServerSnippet{
public static void main(String[] args) throws IOException {
if (args.length == 0) {
System.err.println("Client: java snippet.MyClientServerSnippet<hostname> <port>");
System.err.println("Server: java snippet.MyClientServerSnippet<port>");
System.exit(1);
}
else if (args.length > 1) {
System.out.println("Starting client...\n");
Client client = new Client();
client.cli_main(3049, "127.0.0.1");
} else {
System.out.println("Starting server...\n");
Server server = new Server();
server.svr_main(3049);
}
}
}
Hope this helps :] If anything would be ununderstandable, don't hesitate to ask for more details :)

Java socket client connection and disconnection issue

I made this script:
public class Server {
ServerSocket serv = null;
ObjectInputStream in = null;
ObjectOutputStream out = null;
Socket conn = null;
public Server() {
setLogger(getClass());
setupSocketServer();
listen();
}
public void listen() {
try {
while (true) {
conn = serv.accept();
getLogger().log(new LogRecord(Level.INFO, "Connection established from: " + conn.getInetAddress().getHostAddress()));
out = new ObjectOutputStream(conn.getOutputStream());
in = new ObjectInputStream(conn.getInputStream());
}
}
catch (IOException ex) {
getLogger().log(new LogRecord(Level.SEVERE, "Connection dropped from: " + conn.getInetAddress().getHostAddress()));
}
}
public void setupSocketServer() {
try {
serv = new ServerSocket(Config.PORT_NUMBER, Config.MAX_CONNECTIONS);
getLogger().log(new LogRecord(Level.INFO, "Starting Server on: " + serv.getInetAddress().getHostAddress() + ":" + serv.getLocalPort()));
}
catch (IOException e) {
getLogger().log(new LogRecord(Level.SEVERE, "Socket can not connect to host address"));
System.exit(0);
}
}
public static void main(String[] args) {
new Server();
}
}
But whenever I open my client connection, then close it again and try to re-open, the server has already closed out. I want to be able to keep an infinite connection which allows multiple people to connect. How would I go about doing this?
Try this code for your server,
its made up for multiple client, and the server will remain listening always.
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();
}
}
Move try/catch block into 'while' loop. Not that it' will make a goot server, bit should survive client disconnects.

communication between groovy and java programs through sockets

I am trying to write a small socket program with client side in groovy and the server side in Java. Below is the code I wrote
client:
def s = new Socket("localhost", 4444);
s << "Server before withStreams\n";
s.withStreams { input, output ->
println"Sending message1"
output << "server message1\n"
}
s.close();
server:
import java.io.*;
import java.net.*;
public class Logger{
ServerSocket providerSocket;
Socket connection = null;
BufferedReader in;
String message="InitialMessage";
Logger(){}
void run()
{
try{
providerSocket = new ServerSocket(4444, 10);
try{
Thread.sleep(1000);
}
catch(InterruptedException ie)
{
System.out.println("Sleep Interrupted");
}
System.out.println("Waiting for connection");
connection = providerSocket.accept();
System.out.println("Connection received from " + connection.getInetAddress().getHostName());
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
do{
if(in.ready())
{
try{
System.out.println(in.read());
message = in.readLine();
System.out.println("client>" + message);
}
catch(IOException e)
{
System.out.println(e);
e.printStackTrace();
break;
}
}
} while(!message.equals("bye"));
}
catch(IOException ioException){
ioException.printStackTrace();
}
finally{
//4: Closing connection
try{
in.close();
providerSocket.close();
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
}
public static void main(String args[])
{
Logger server = new Logger();
while(true){
server.run();
}
}
}
When I execute both programs, Socket communication is established. But I get a IOException in server code when it reads from the socket (message = in.readLine();)
I guess there is some format problem in writing into socket in client. But not able to figure out the exact problem. Can anybody help?
You generally don't want to close your ServetSocket for each client connection. You want to do this once (or every time you start the server) then on each accept() handle the client connection and close the socket for that connection but keep the ServerSocket open until you want to stop the server.
Here's a rewritten version of your example server that also creates a new Thread for each client request to handle multiple concurrent requests. Note that since the test client doesn't send the terminating string "bye" the connection and socket stays open.
import java.io.*;
import java.net.*;
public class Logger {
private ServerSocket providerSocket;
Logger() {
}
public void start() {
try {
providerSocket = new ServerSocket(4444, 10);
while (true) {
System.out.println("Waiting for connection");
Socket connection = providerSocket.accept();
new Thread(new Job(connection)).start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (providerSocket != null) {
System.out.println("Stopping server");
try {
providerSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
static class Job implements Runnable {
final Socket connection;
private static int id;
private int clientId = ++id;
public Job(Socket connection) {
this.connection = connection;
}
public void run() {
BufferedReader in = null;
try {
System.out.println("Connection " + clientId + " received from " + connection.getInetAddress().getHostName());
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String message = "InitialMessage";
do {
if (in.ready()) {
try {
// not sure why want to read one character then read the line
//int ch = in.read();
//System.out.println(ch);
// -1 if the end of the stream has been reached
//if (ch == -1) break;
message = in.readLine();
// null if the end of the stream has been reached
if (message == null) break;
System.out.println("client>" + message);
} catch (IOException e) {
System.out.println(e);
e.printStackTrace();
break;
}
}
} while (!message.equals("bye"));
} catch (IOException e) {
e.printStackTrace();
} finally {
//4: Closing connection
System.out.println("Close connection " + clientId);
if (in != null)
try {
in.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
try {
connection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String args[]) {
Logger server = new Logger();
server.start();
}
}

Categories

Resources