I am trying to reproduce "java.net.SocketException.Connection reset" exception.
Wanted to know if there is any program available which could help me simulate it. I tried following Server and client programs to see if I could simulate but I am not able to get any exception. I am using java8.
Server Code-
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
public class SimpleServerApp {
public static void main(String[] args) throws InterruptedException {
new Thread(new SimpleServer()).start();
}
static class SimpleServer implements Runnable {
#Override
public void run() {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(3333);
serverSocket.setSoTimeout(0);
//serverSocket.
while (true) {
try {
Socket clientSocket = serverSocket.accept();
BufferedReader inputReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("Client said :"+ inputReader.readLine());
} catch (SocketTimeoutException e) {
e.printStackTrace();
}
}
}catch (Exception e) {
e.printStackTrace();
System.out.println(" EXCEPTION " + e.getStackTrace());
}/*catch (IOException e1) {
e1.printStackTrace();
}*/ /*finally {
try {
if (serverSocket != null) {
serverSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}*/
}
}
}
Client Code -
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
public class SimpleClientApp {
public static void main(String[] args) {
new Thread(new SimpleClient()).start();
}
static class SimpleClient implements Runnable {
#Override
public void run() {
Socket socket = null;
try {
socket = new Socket("localhost", 3333);
PrintWriter outWriter = new PrintWriter(socket.getOutputStream(), true);
System.out.println("Wait");
Thread.sleep(20000);
//System.exit(0);
//throw new Exception("Random exception");
//socket.close();
outWriter.println("Hello Mr. Server!");
}catch (SocketException e) {
e.printStackTrace();
}catch (InterruptedException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} /*finally {
try {
if (socket != null)
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
*/ }
}
}
Scenario 1.
Start the server program locally.
Start the Client program locally.
Close the client program abruptly (Ctrl C) - I just get output on
Server program "Client said :null"
Scenario 2.
Start the Server program Locally.
Start the client program locally.
Client is connected to server, Then while client program is waiting close the server program abruptly. Still no exception.
Can some tell me some way I could produce the connection reset exception, With working sample code.
None of the answers above worked for me reliably both on Mac and Linux.
After a lot of Googling, I ended with this article explaining how to do it. Just to be clear: I was trying to reproduce the connection reset from the client side, i.e. "Connection reset by peer".
I tried bringing up a process which run netcat, and abruptly killing the process - that only worked on Mac.
I tried socket.close from another thread, same thread - nothing worked.
Simply, all those methods didn't cause the client to send RST to the server, which causes the exception (reset by peer).
The following worked:
Setup any server - in my case Netty (their getting started Discard server will do).
Use the following client code:
final Socket socket = new Socket("localhost", port);;
socket.setSoLinger(true, 0);
final OutputStream outputStream = socket.getOutputStream();
for (int i=0; i <= 500; i++) {
outputStream.write('a');
}
outputStream.write('\n');
outputStream.flush();
socket.close();
Thread.sleep(2000);
The soLinger() was the magic trick. According to the Oracle article cited above, when you call socket.close() it sends a RST to the other side, instead of sending FIN and then waiting for the other side to finish reading what ever was sent until the FIN - i.e. force close.
It took me 1 day of work to find this out, so I hope it will save you time on your work.
There are several ways. I won't post one of them as it is too much abused, but the simple ways to produce it are:
Close a socket immediately you acquire it, without reading anything. This works if the sender is sending to you rather than reading from you.
If you know the sender has sent something, close the socket without reading it in any way.
This works for me:
class Server {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(9999);
Socket s = ss.accept();
InputStream i = s.getInputStream();
i.read();
}
}
client connects and disconnects without closing socket
class Client {
public static void main(String[] args) throws Exception {
Socket s = new Socket("localhost", 9999);
}
}
this results in exception on server
Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at net.Server.main(Server.java:13)
Instead of provoking this exception using Java client code, I found it easier to just write a short Python script:
import struct, socket
s = socket.socket(socket.AF_INET6)
s.connect(("::1", 8000))
s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack('ii', 1, 0))
s.close() # provokes Connection Reset at host
Related
If I have a server and a client and I opened a socket between the two:
1.Is it possible that the client will have a printWriter stream, in order to write things to the socket, but the server won't have in the mean time a bufferReader?
If the answer of 1 is yes, if that client will send a message to the server (who currently doesn't have a reading stream), what will happend to this message until te server will create a reading stream and read the message?
thank you
This is not at all specific to Java, but TCP/IP. There are buffers to keep the data received, so it's not possible that some data would be lost because one end isn't "ready" yet. This is because TCP will retransmit data that hasn't been acknowledged as received, guaranteeing that all the bytes that are written are received on the other (barring obvious cases).
in addition to #Kayaman's answer:
consider this Compile-able simple Java implemented example:
Server Side:
import java.io.*;
import java.net.*;
public class SimpleServer implements Runnable{
int serverPort = 45000;
ServerSocket serverSocket = null;
boolean isStopped = false;
public SimpleServer(int port){
this.serverPort = port;
}
public void run(){
try {
serverSocket = new ServerSocket(serverPort);
} catch (IOException e) {
System.err.println("Cannot listen on this port.\n" + e.getMessage());
System.exit(1);
}
while(!isStopped){
try {
Socket clientSocket = serverSocket.accept();
} catch (IOException e) {
// do nothing
}
}
}
public static void main(String[] args) throws IOException {
SimpleServer server = new SimpleServer(45000);
new Thread(server).start();
System.out.println("Server is waiting to connect");
}
}
Client Side:
import java.io.*;
import java.net.*;
public class SimpleClient {
public static void main(String[] args) throws IOException {
Socket socket = null;
PrintWriter out = null;
try {
socket = new Socket("127.0.0.1", 45000);
out = new PrintWriter(socket.getOutputStream(), true);
System.out.println("output stream created");
out.write(9);
System.out.println("message was sent to output with no listener");
} catch (UnknownHostException e) {
// do nothing
} catch (IOException e) {
// do nothing
}
}
}
the example is an implementation of a very basic client server connection in which a socket is created and a stream is defined only on the client side, followed by a write to the stream that will eventually be read by the server (if at all).
therefore, to answer you questions:
1) yes, it's possible to open a one-way connection stream without a "listener"
2) edit: according to #EJP: It will be saved within the socket's buffer until it is read or the socket is closed.
I am new to java and network programming for the most part. I want to write a program that automatically backs up my texts to my computer whenever my phone connects to my home wifi.
I am working on creating java classes that will handle sending data over the network. Using some questions found here, I came up with this implementation but I have some questions regarding some of the methods used in what I learned from.
Two Questions Regarding this code
I totally used a question from SO for the send methods in my client. The sendText uses a new thread, but the sendFile doesn't. Any particular reason why?
2. At which point in the code does the server actually know when there has been a message sent to the port? Is it at the method accept() call or is it when the BufferStream readLine() is checked? Does accept just grab data and throw it into the buffer? null implying the data grabbed was not a signal sent from a client?
Does the accept() method block execution of the code until a connection attempt is made from a client?
Thanks!
KServ
//Used to launch the server
public class KServ {
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Usage: java KServ <port number>");
System.exit(1);
}
int port = Integer.parseInt(args[0]);
KServer server = new KServer(port);
while (true) { //added this to keep the server polling for new data
server.run();
}
}
}
KServer
//Server class. Should handle data incoming
import java.net.*;
import java.io.*;
public class KServer {
private int port;
public KServer(int PORT) {
port = PORT;
}
public void run() {
try (
ServerSocket sSocket = new ServerSocket(port);
Socket cSocket = sSocket.accept();
PrintWriter out = new PrintWriter(cSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(cSocket.getInputStream()));
) {
String input;
while ((input = in.readLine()) != null) {
System.out.println(input);
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port " + port + " or listening for a connection");
System.out.println(e.getMessage());
}
}
}
Client
//launches KClient object and uses it to send input from console to the server
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
if (args.length != 2) {
System.err.println("Usage: java Client <ip number> <port number>");
System.exit(1);
}
String ip = args[0];
int port = Integer.parseInt(args[1]);
KClient client = new KClient(ip,port);
String msg;
Scanner inStream = new Scanner(System.in);
while((msg = inStream.nextLine()).length() > 0) {
client.sendText(msg);
}
}
}
KClient
//Will be used to establish connection with server and send data from phone
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class KClient {
private String server;
private int port;
public KClient(String Server,int Port) {
server = Server;
port = Port;
}
public void sendFile(String fileName) {
File file = new File(fileName);
FileInputStream fileInputStream;
BufferedInputStream bufferedInputStream;
OutputStream outputStream;
try {
client = new Socket(server,port);
byte[] bytes = new byte[(int) file.length()];
fileInputStream = new FileInputStream(file);
bufferedInputStream = new BufferedInputStream(fileInputStream);
bufferedInputStream.read(bytes, 0, bytes.length);
outputStream = client.getOutputStream();
outputStream.write(bytes,0,bytes.length);
outputStream.flush();
bufferedInputStream.close();
outputStream.close();
client.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private Socket client;
private OutputStreamWriter outputStreamWriter;
public void sendText(String msg) {
System.out.println("Send Message!");
new Thread(new Runnable() {
#Override
public void run() {
try {
client = new Socket(server,port);
outputStreamWriter = new OutputStreamWriter(client.getOutputStream(), "ISO-8859-1");
outputStreamWriter.write(msg);
outputStreamWriter.flush();
outputStreamWriter.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
BufferedReader inStream;
public boolean Shake() {
try {
client = new Socket(server,port);
inStream = new BufferedReader(new InputStreamReader(client.getInputStream()));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
}
I totally used a question from SO for the send methods in my client. The sendText uses a new thread, but the sendFile doesn't. Any particular reason why?
Unanswerable. Ask the author. Both sends can block. As the file is presumably longer than the text, it would have made more sense to do it the other way round.
2. At which point in the code does the server actually know when there has been a message sent to the port? Is it at the method accept() call
No.
or is it when the BufferStream readLine() is checked?
Yes.
Does accept just grab data and throw it into the buffer?
No. It grabs a connection and returns it as a socket. Nothing to do with data whatsoever.
null implying the data grabbed was not a signal sent from a client?
You seem to be actually asking about BufferedReader.readLine() here, not ServerSocket.accept(), which doesn't return null. readLine() returns null when there is no pending data to be read and the peer has closed the connection.
Does the accept() method block execution of the code until a connection attempt is made from a client?
More or less. It blocks until there is a complete connection waiting to be accepted, which isn't quite the same thing, as there is a queue.
I will add that you have copied, or written, some truly terrible code here. There are much better examples.
I was working on multi-client sockets and its working just fine, however it came to my mind on how to make the communication public by making the entered string being streamed to all clients.
e.g if there are lets say 3 clients A,B and C and client A sends "foo" to server, I want the server to stream "foo" to clients B and C as well.
The Server Module :
package multiclient;
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 {
public static void main(String args[]) {
Socket s = null;
ServerSocket ss2 = null;
System.out.println("Server Listening......");
try {
ss2 = new ServerSocket(4445); // can also use static final PORT_NUM , when defined
} catch (IOException e) {
e.printStackTrace();
System.out.println("Server error");
}
while (true) {
try {
s = ss2.accept();
System.out.println("connection Established");
ServerThread st = new ServerThread(s);
st.start();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Connection Error");
}
}
}
}
class ServerThread extends Thread {
String line = null;
BufferedReader is = null;
PrintWriter os = null;
Socket s = null;
public ServerThread(Socket s) {
this.s = s;
}
public void run() {
try {
is = new BufferedReader(new InputStreamReader(s.getInputStream()));
os = new PrintWriter(s.getOutputStream());
} catch (IOException e) {
System.out.println("IO error in server thread");
}
try {
line = is.readLine();
while (line.compareTo("QUIT") != 0) {
os.println(line);
os.flush();
System.out.println("Response to Client : " + line);
line = is.readLine();
}
} catch (IOException e) {
line = this.getName(); //reused String line for getting thread name
System.out.println("IO Error/ Client " + line + " terminated abruptly");
} catch (NullPointerException e) {
line = this.getName(); //reused String line for getting thread name
System.out.println("Client " + line + " Closed");
} finally {
try {
System.out.println("Connection Closing..");
if (is != null) {
is.close();
System.out.println(" Socket Input Stream Closed");
}
if (os != null) {
os.close();
System.out.println("Socket Out Closed");
}
if (s != null) {
s.close();
System.out.println("Socket Closed");
}
} catch (IOException ie) {
System.out.println("Socket Close Error");
}
}//end finally
}
}
The Client Module:
package multiclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
public class Client {
public static void main(String args[]) throws IOException{
InetAddress address=InetAddress.getLocalHost();
Socket s1=null;
String line=null;
BufferedReader br=null;
BufferedReader is=null;
PrintWriter os=null;
try {
s1=new Socket(address, 4445); // You can use static final constant PORT_NUM
br= new BufferedReader(new InputStreamReader(System.in));
is=new BufferedReader(new InputStreamReader(s1.getInputStream()));
os= new PrintWriter(s1.getOutputStream());
}
catch (IOException e){
e.printStackTrace();
System.err.print("IO Exception");
}
System.out.println("Client Address : "+address);
System.out.println("Enter Data to echo Server ( Enter QUIT to end):");
String response=null;
try{
line=br.readLine();
while(line.compareTo("QUIT")!=0){
os.println(line);
os.flush();
response=is.readLine();
System.out.println("Server Response : "+response);
line=br.readLine();
}
}
catch(IOException e){
e.printStackTrace();
System.out.println("Socket read Error");
}
finally{
is.close();os.close();br.close();s1.close();
System.out.println("Connection Closed");
}
}
}
The server can keep a collection of all client sockets (until one is closed). When a client message arrives, server writes it to all client sockets.
There's a problem though, socket.write() is blocking, so if we do it in a loop, a slow client will block the rest of the clients. You can spawn a new thread to write to each individual socket, if there aren't too many clients.
In the blocking IO world, to implement a true full-duplex protocol, it is necessary for server to have two threads per client, one for read, one for write.
You may also try NIO if you are brave enough...
There are many examples. Search for chat server. One good one if you don't mind using a framework is Netty, check the SecureChat example for working code. It is a short and focused example.
Edit: the link takes you to the example code.
I suggest:
1. Keep the threads you create in an ArrayList
2. Create a method in Server called writeString and a lock
private final Lock mutex = new ReentrantLock(true);
private ArrayList<ServerThread> list = new ArrayList<ServerThread>();
public void writeString(ServerThread t,String s)
{
mutex.lock();
for(ServerThread th:list)
if(th!=null && th!=t) //different from the thread receiving the string
th.writeString(s); //send string to other threads
mutex.unlock();
}
3. in ServerThread class, implement writeString method and add a Lock
private final Lock mutex = new ReentrantLock(true);
public void writeString(String s)
{
mutex.lock();
os.println(s);
os.flush();
mutex.unlock();
}
4. Keep a reference to the main Server thread by modifying the constructor
//in ServerThread
private Server parent=null;
SeverThread(Socket s, Server parent)
{
this.parent=parent;
/*the rest of the code*/
}
//in Server
ServerThread st = new ServerThread(s,this);
st.start();
list.add(st);
When you read the string in ServerThread, call the Server writeString method in order to notify all the clients
parent.writeString(this,s); //calls the method we created at 2.
I managed to setup a server which will accept & manage multiple socket clients.
but now when I try to send a message, the server just doesn't receive anything, yet I do flush the message.
This is the method that's managing the clients:
public void run() {
while(true) {
for (Client c : this.clients) {
try {
if (c.getStream().read() != -1) {
if (c.getInputStream() != null) {
System.out.println("He sent message");
c.sendMessage("hey client");
}
}
} catch (IOException e) {
c.destruct();
this.clients.remove(c); break;
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Client list:
public ArrayList<Client> clients = new ArrayList<Client>(); // client list
And Client object:
public class Client {
private Socket socket;
private int clientId;
private BufferedReader inStream;
private PrintWriter outStream;
private boolean socketAlive = true;
public Client(Socket sock) {
this.socket = sock;
}
public void setup() {
setInputOutputStream();
System.out.println("New connection: " + this.getIpAddress());
this.sendMessage("Successfully connected!");
}
public BufferedReader getStream() {
return this.inStream;
}
public String getInputStream() {
String toReturn = "";
try {
toReturn = this.inStream.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return toReturn;
}
public void destruct() {
try {
this.inStream.close();
this.inStream = null;
this.outStream.close();
this.outStream = null;
System.out.println("Client destruct: " + this.socket.getLocalSocketAddress());
this.socket.close();
this.socket = null;
} catch (IOException e) {
e.printStackTrace();
}
}
public Socket getConnection() {
return this.socket;
}
private void setInputOutputStream() {
try {
inStream = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
outStream = new PrintWriter(this.socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendMessage(String s) {
this.outStream.println(s);
this.outStream.flush();
}
public String getIpAddress() {
return this.socket.getRemoteSocketAddress().toString();
}
}
And the client side (sender) :
public static void main(String[] args) {
try {
System.out.println("Client started");
Socket sock = new Socket("localhost", 43594);
Scanner scanner = new Scanner(System.in);
String input;
PrintWriter out = new PrintWriter(sock.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
while (true) {
input = scanner.nextLine();
if (input != null) {
out.print(input);
out.flush();
}
}
} catch (IOException e) {
System.out.println("Client error");
}
}
Why is my server not receiving anything?
One thing:
If I send message + disconnect, this what the server will log (It looks like it only sends the message upon disconnect or something, well no, it enters the if block only upon it):
Server is successfully running on port 43594
New connection: /127.0.0.1:57102
He sent message
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at Client.getInputStream(Client.java:32)
at ClientHandler.run(ClientHandler.java:21)
Client destruct: 0.0.0.0/0.0.0.0:43594
What did I do wrong? how can I fix that
Server (main class)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.*;
import java.util.ArrayList;
public class Server {
private int port = 43594;
public void listen() {
System.out.println("Trying to listen...");
try {
final ServerSocket server = new ServerSocket(port);
// Create new thread to handle clients I/O
ClientHandler handler = new ClientHandler(server);
// START it
handler.start();
System.out.println("Server is successfully running on port " + port);
while (true) {
// New connection found create a new Client object
Client cl = new Client(server.accept());
cl.setup();
// add it to clietns list in the I/O handler
handler.clients.add(cl);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
// start up
System.out.println("Starting up..");
// server instance
final Server server = new Server();
// create a new thread for server
new Thread(new Runnable() {
#Override
public void run() {
// listen for new connections
server.listen();
}
}).start();
}
}
The client is sending data and the servers is reading.
I think the problem is in Client.getInputStream
this.inStream.readLine(), it reads a line of text.
From documentation:
"Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed."
http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html
If you use read instead, maybe it is going to work. Just use a kind of protocol like sending first 1 or 2 bytes with the length of the message. Or you may send a '\n' from the client.
BTW, the reason for the exception in the server when you send and disconnect in the client side may be due to a TCP fact. The client closed the connection and it probably received a TCP ACK from the server. Then TCP in the client sends a RESET segment. Not so sure though. The server was at this.inStream.readLine() and then it received an exception. Didn't you also received "Connection closed by peer"?
I am not sure why, but I needed to use out.println(input) out.flush() instead of .print() or .write()
I don't have an explanation of why do I need to do that. but it worked.
I think the problem comes from the fact that you've got a list of clients and are trying to manage them with that. I looked up java.net.SocketException: Connection reset, and found this question: What's causing my java.net.SocketException: Connection reset?
The answer to this question comes up with this:
In your case it seems that the connection has been closed by the
server end of the connection. This could be an issue with the request
you are sending or an issue at their end.
This made me think that you aren't holding the connection to the client every time. You store it, and then you lose it, so the message isn't sent. To handle more clients, you might rather want to have a list of IPs, rather than clients, and then you connect when you want to send a message. You can't store the Socket connection. It has to be active. Java (The JVM) has it's own "Garbage Collection" system that'll just kill it.
i try creating client-server app using socket.
i already succeed doing that with the AVD and run both server and client on my pc machine.
but when i try make it work in same Wifi network on my device, the app just crash.
yes, i'm using seperate thread for the connection
and already added the use of Internet to the manifest.
here is some code...
the client thread:
package com.mainlauncher;
import java.io.*;
import java.net.*;
public class ConnectionThread extends Thread {
private static final int SERVERPORT = 7777;
private static final String SERVERADDRESS = "My-PC";
private Socket socket;
private DataInputStream in;
private DataOutputStream out;
#Override
public void run() {
super.run();
open();
close();
}
void open(){
try{
socket = new Socket(SERVERADDRESS,SERVERPORT);
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
}
catch(IOException e){}
}
void close(){
try {
if(in!=null)
in.close();
if(out!=null)
out.close();
if(socket!=null)
socket.close();
}
catch (IOException e) {}
socket=null;
}
}
the Server side main:
import java.io.IOException;
import java.net.*;
public class Main {
public static void main(String[] args) {
int port = 7777;
new Main().handleClients(port);
}
private void handleClients(int port) {
ServerSocket serverSocket = null;
try{
serverSocket = new ServerSocket(port);
System.out.println("Server is ready...");
for(int i=1; ; i++){
Socket socket = serverSocket.accept();
ServerThread thread = new ServerThread(i,socket);
System.out.println(i + " Connected");
thread.run();
}
}
catch (Exception e){
System.err.println(e.getMessage());
}
finally{
if(serverSocket != null){
try{ serverSocket.close(); }
catch(IOException x){}
}
}
}
}
and the ServerThread:
import java.io.*;
import java.net.*;
public class ServerThread extends Thread {
private int serverIndex;
private Socket socket;
private DataOutputStream out;
private DataInputStream in;
public ServerThread (int serverIndex, Socket socket){
this.serverIndex = serverIndex;
this.socket = socket;
}
#Override
public void run() {
super.run();
try {
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
} catch (IOException e) {
System.out.println(serverIndex + " Disconnected");
}
finally{
try {
in.close();
out.close();
socket.close();
} catch (IOException e) {}
}
}
}
i tried looking for answers here \ google etc...
nothing helped.
there is no firewall or anything to block the incoming connection on my pc.
any ideas anyone?
thanks,
Lioz
This won't immediately solve your problem, but you have a couple of bugs that are causing your program to throw away the evidence of the the real problem.
1) This simply squashed the exception, throwing away all evidence that it ever happened.
catch(IOException e){}
2) This is a bit better, but it only prints out the exception message ... not the stack trace.
catch (Exception e){
System.err.println(e.getMessage());
}
The other problem with 2) is that it catches ALL exceptions ... not just IOExceptions. That includes unchecked exceptions like NullPointerException, SecurityException and so on.
Exceptions should be diagnosed like this:
catch (IOException e){
e.printStackTrace();
}
or logged.
Finally, the way that you are handling requests is wrong:
Socket socket = serverSocket.accept();
ServerThread thread = new ServerThread(i,socket);
System.out.println(i + " Connected");
thread.run();
The mistake is in the last statement. What this actually does is to simply call the thread object's run() method ... in the current thread. To run the run() method in a different thread you need to call the start method. Like this:
Socket socket = serverSocket.accept();
ServerThread thread = new ServerThread(i,socket);
System.out.println(i + " Connected");
thread.start();