Why SocketException? - java

I have Client class and Server class but when i run both main methods and then nothing will happen and when i stop running ,this exception will be occurred. why?? please help me,how can I fix it???
my Client class:
public class Client {
static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try {
Socket c = new Socket("localhost", 5001);
BufferedReader read = new BufferedReader(new InputStreamReader(c.getInputStream()));
BufferedWriter write = new BufferedWriter(new OutputStreamWriter(c.getOutputStream()));
String string = reader.readLine();
write.write(string, 0, string.length());
write.newLine();
write.flush();
System.out.println(read.readLine());
} catch (Exception e) {
System.err.println(e);
}
}}
my Server class:
public class Server{
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
ServerSocket s = null;
try {
s = new ServerSocket(5001);
System.out.println("listening...");
Socket so = s.accept();
BufferedReader read = new BufferedReader(new InputStreamReader(so.getInputStream()));
BufferedWriter write = new BufferedWriter(new OutputStreamWriter(so.getOutputStream()));
while (true) {
String string = read.readLine();
System.out.println(string);
String answer = "I got" + string + "from you!";
write.write(answer, 0, answer.length());
write.newLine();
write.flush();
}
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}}
stacktrace in server cpnsole:
run:
listening...
system connected
Hello
Dec 19, 2009 12:58:15 PM server.Main main
SEVERE: null
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:168)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:264)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:306)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:158)
at java.io.InputStreamReader.read(InputStreamReader.java:167)
at java.io.BufferedReader.fill(BufferedReader.java:136)
at java.io.BufferedReader.readLine(BufferedReader.java:299)
at java.io.BufferedReader.readLine(BufferedReader.java:362)
at server.Main.main(Main.java:37)
BUILD SUCCESSFUL (total time: 9 seconds)
in Client console:
run:
Hello
I gotHellofrom you!
BUILD SUCCESSFUL (total time: 4 seconds)

Your client connects to the server, sends some data, reads the response and terminates. That's ok.
But your server waits for a client, reads its data, writes a response and then tries to read some data from the client again. But the client has closed the connection. So the server gets the exception you described.
To fix this (on server side), you have to do the Socket so = s.accept(); within your while loop. And don't forget to close the socket at the end of the loop.

First. A BufferedWriter isn't useful with Sockets. Use a PrintWriter witch flushes automatically.
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);// true means "flush automatically"
writer.println(reader.readLine());
// Now you don't have to add a newline and flush.
Edit
Secondly. The reason why the exception is thrown is because the client closes the Socket after writing your input to the Server. The server is still waiting for another String to read. But he can't because the Socket is closed. You don't close it literally. But the program ends there. So Java think: "Nothing left to do, exit". By exiting, the connection closes.
To solve it you have to put the communication in a while(true) loop and, to stop the connection in a correct way, send an "end-of-connection" message.
Client side:
while (true)
{
String userinput = reader.readLine(); // From System.in
writer.writeln(userinput);
if (userinput.equals("end"))
{
socket.close();
break; // break out of the while(true) loop
}
}
Server side:
while (true) {
String socketinput = reader.readLine();
if (socketinput.equals("end"))
{
socket.close();
break; // Break out of the while(true) loop.
}
... // Handle the socketInput
}
That is also what "Connection reset" means.
Martijn.

Related

Input/output codes execution (what's executed first, the client or the server?)

We just started studying IO codes and there is a certain point I don't understand this problem :
Here's the server Code :
public final class SuccServer {
public static void main(String[] args) {
try (ServerSocket s0 = new ServerSocket(5108);
Socket s = s0.accept();
BufferedReader r =
new BufferedReader(
new InputStreamReader(s.getInputStream(),
US_ASCII));
BufferedWriter w =
new BufferedWriter(
new OutputStreamWriter(s.getOutputStream(),
US_ASCII))) {
int i = Integer.parseInt(r.readLine());
int i1 = i + 1;
w.write(String.valueOf(i1));
w.write('\n');
w.flush();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
And here's the Client code :
public final class SuccClient {
public static void main(String[] args) {
try (Socket s = new Socket("localhost", 5108);
BufferedReader r =
new BufferedReader(
new InputStreamReader(s.getInputStream(),
US_ASCII));
BufferedWriter w =
new BufferedWriter(
new OutputStreamWriter(s.getOutputStream(),
US_ASCII))) {
int i = 2019;
w.write(String.valueOf(i));
w.write('\n');
w.flush();
int succ = Integer.parseInt(r.readLine());
System.out.printf("succ(%d) = %d%n", i, succ);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
First the connection is established so the accept() creats the socket, then I don't understand how the code will work(chronologically), why is the client's write instruction
w.write(String.valueOf(i));
that is executed first and not the server's
int i = Integer.parseInt(r.readLine());
, and why after writing 2019 does the client wait for the server's response ? he could simply continue the code by executing
int succ = Integer.parseInt(r.readLine());
without waiting for the server to respond him with 2020 ?
These questions could seem simple but they don't let me understand more difficult code.
Simply put it's because readLine() and accept() are blocking.
"In computing, a process is an instance of a computer program that is being executed. A process always exists in exactly one process state. A process that is blocked is one that is waiting for some event, such as a resource becoming available or the completion of an I/O operation"
Program would hang at readline() until newline or end of stream is reached, just like when accept() is called on the server it hangs until a client connects.
edit: Here is another explanation with focus on network sockets.

Trying to Get a new ServerSocket to open fails

I was given the below code by my teacher for a class. I ran it one or twice and it worked fine. However I suddenly cannot get it to run from the command prompt on Windows 8 anymore. No matter what port I specify it just prints "Opening port..." and never continues. No exception is ever thrown. I have disabled my firewall and antivirus and it does not seem to work. I have added a print statement as the first line of the try catch block and it will print but it just will not create the new Socket. I am sure it is something in my Windows settings but I am unsure as to what or how to resolve it.
// Server program
// File name: "TCPServer.java"
import java.io.*;
import java.net.*;
public class TCPServer
{
private static ServerSocket servSock;
public static void main(String[] args)
{
System.out.println("Opening port...\n");
try{
// Create a server object
servSock = new ServerSocket(Integer.parseInt(args[0]));
}
catch(IOException e){
System.out.println("Unable to attach to port!");
System.exit(1);
}
do
{
run();
}while (true);
}
private static void run()
{
Socket link = null;
try{
// Put the server into a waiting state
link = servSock.accept();
// Set up input and output streams for socket
BufferedReader in = new BufferedReader(new InputStreamReader(link.getInputStream()));
PrintWriter out = new PrintWriter(link.getOutputStream(),true);
// print local host name
String host = InetAddress.getLocalHost().getHostName();
System.out.println("Client has estabished a connection to " + host);
// Receive and process the incoming data
int numMessages = 0;
String message = in.readLine();
while (!message.equals("DONE"))
{
System.out.println(message);
numMessages ++;
message = in.readLine();
}
// Send a report back and close the connection
out.println("Server received " + numMessages + " messages");
}
catch(IOException e){
e.printStackTrace();
}
finally{
try{
System.out.println("!!!!! Closing connection... !!!!!\n" + "!!! Waiting for the next connection... !!!");
link.close();
}
catch(IOException e){
System.out.println("Unable to disconnect!");
System.exit(1);
}
}
}
}
This code works fine. The problem is the code for the client. The answer to your problem is already written in a comment in your code.
// Put the server into a waiting state
link = servSock.accept();
The server goes into a waiting state until it gets a connection. The client is the one that would be getting the error since it did not connect. If the client was working correctly the code would continue and you would get the additional output.

SocketTimeoutException in client readLine() method on AWS

UPDATE:
I noticed that it works fine on a Windows machine, but it fails on Mac.
I created a basic Java Server code for socket connection. It runs on AWS Linux AMI, and I make a client connection from my computer. It works fine for first 4-5 answers from the client. However, after 4th or 5th answer, I don't get any response from the server and it just hangs. After a while, it gives SocketTimeout Exception.
I set socket timeout with setSoTimeout() in both side, and it didn't change anything. I wonder if it has anything to do with Amazon.
Client Code:
public static void main(String[] args) {
final int portNumber = 9090;
String connected = "1";
System.out.println(WELCOME);
try {
Socket socket = new Socket("ip", portNumber);
socket.setSoTimeout(0);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader input = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
out.println(connected);
while (connected.equals("1")) {
//read in situation
String situation = readInSituation(socket, input).replace(DELIMETER, "\n");
System.out.println(situation);
//send option
Scanner in = new Scanner(System.in);
System.out.print("Enter option: ");
out.println(in.nextLine());
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static String readInSituation(Socket socket, BufferedReader input) throws Exception {
while (!input.ready()) {
Thread.sleep(200);
}
return input.readLine();
}
Server Code is more complicated, but all it does is to respond to commands and print basic text on the screen.
Thanks
Don't use PrintWriter over the network, as it swallows exceptions, most probably a prior 'connection reset'. Use BufferedWriter. NB The ready() loop is literally a waste of time.

Issue with sending multiple commands over a socket connection

I'm trying to send a command and have it execute through a socket connection. I need to read each response line, then continue sending commands to the same process. Below I have the methods that handle that.
Currently, I receive a response when I initially open the socket connection, but after, the program hangs until the foreign host closes the connection, presumably because no input was entered in a specified amount of time.
public static void main(String[] args) {
try {
sendSmtpTest("anEmail#aRandomDomain");
} catch (Exception e) {
e.printStackTrace();
}
}
public static boolean sendSmtpTest(String address) throws Exception {
Socket socket = new Socket("a.random.address", 0000);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
int res;
System.out.println("1");
System.out.println(in.readLine());
System.out.println("2");
System.out.println(in.readLine());
say(out, "HELO netatlantic.com");
System.out.println("3");
System.out.println(in.readLine());
System.out.println("4");
System.out.println(in.readLine());
say(out, "MAIL FROM: <abuse#netatlantic.com>");
System.out.println("5");
System.out.println(in.readLine());
say(out, "RCTP TO: <" + address + ">");
System.out.println("6");
System.out.println(in.readLine());
say(out, "RSET");
System.out.println("7");
say(out, "QUIT");
// clean up
in.close();
in.close();
out.close();
return true;
}
private static void say(BufferedWriter wr, String text) throws IOException {
wr.write((text + "\r\n"));
wr.newLine();
wr.flush();
}
The random printing of the numbers are a way for me to know where in the program it is at. Also, I have to run this off of a server, thus I cannot run it in a debugger because the socket I'm connecting to only accepts connections from a specific address.
Thanks!
You mean that you see the 220 status from the SMTP server print out, but then it just hangs?
That's because you are waiting for another line to be sent from the server, but it's waiting for your HELO command. (Right after your "2" statement.) Remove that extra System.out.println(in.readLine()); and see if you make progress.
If not, post the output from your program so that your question is more understandable.

What determines in this code what is sent back to the client? TCP Sockets

In the code below, what determines what will be sent back to the client (the PHP page). I am trying to alter this so that it sends a variable back to the PHP page with an error message that is defined based on actions made in my java code.
Edit: To answer some questions, what I am trying to do is this.
Send a string to the java script with a socket and convert it to a variable to be used in the java script. It will run through some if statements and I need to set the error statements to a variable lets say "reply". I need to send "reply" then back to the PHP file.
public class MyJavaServer {
public static void main(String[] args) {
int port = 20222;
ServerSocket listenSock = null; //the listening server socket
Socket sock = null; //the socket that will actually be used for communication
try {
listenSock = new ServerSocket(port);
while (true) { //we want the server to run till the end of times
sock = listenSock.accept(); //will block until connection recieved
BufferedReader br =
new BufferedReader(new InputStreamReader(sock.getInputStream()));
BufferedWriter bw =
new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
String line = "";
while ((line = br.readLine()) != null) {
bw.write("PHP said: " + line + "\n");
bw.flush();
}
//Closing streams and the current socket (not the listening socket!)
bw.close();
br.close();
sock.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
If I get your question right, the line where the answer gets sent to the peer is
bw.write("PHP said: " + line + "\n");
which writes the given string to bw.

Categories

Resources