java.net.SocketException: Connection reset , anyone help me - java

I was learning tcp/ip protocol and i wrote a program yesterday. It's a simple code , client send a string, server receive and print it to console . but when i start , this become error . Anyone check it for me , please . Here's my code .
Client side :
public class Client {
Socket client ;
DataInputStream is;
DataOutputStream os;
public Client(){
try {
client=new Socket("localhost", 7777);
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void send(String txt){
try {
os=new DataOutputStream(client.getOutputStream());
if(os!=null && client!=null)
os.writeBytes(txt);
System.out.println("Send OK");
close();
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void close(){
if(client!= null&& os!= null&& is!= null) {
try{
os.close();
is.close();
client.close();
}
catch(UnknownHostException e) {
System.err.println(e);
} catch(IOException e) {
System.err.println(e);
}}}}
Client main :
public static void main(String[] args) {
// TODO code application logic here
Client client=new Client();
client.send("hehea");
}
and the server :
public class ServerTCP {
PrintStream os;
DataInputStream is;
Socket client;
ServerSocket myserver;
public void open(){
try {
myserver=new ServerSocket(7777);
System.out.println("Open Server ");
client=myserver.accept();
listen();
} catch (IOException ex) {
Logger.getLogger(ServerTCP.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void listen(){
try {
System.out.println("\nListenning....");
is=new DataInputStream(client.getInputStream());
os=new PrintStream(client.getOutputStream());
String txt="";
ReverseString result = null;
while(true)
{
result=new ReverseString(is.readLine());
System.out.println(is.readLine());
}
} catch (IOException ex) {
Logger.getLogger(ServerTCP.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Server main
public static void main(String[] args) {
// TODO code application logic here
ServerTCP server=new ServerTCP();
server.open();
Finally , error in console
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:196)
at java.net.SocketInputStream.read(SocketInputStream.java:122)
at java.net.SocketInputStream.read(SocketInputStream.java:210)
at java.io.DataInputStream.readLine(DataInputStream.java:513)
at daochuoiservertcp.ServerTCP.listen(ServerTCP.java:50)
at daochuoiservertcp.ServerTCP.open(ServerTCP.java:34)
at daochuoiservertcp.Server.main(Server.java:21)

You're reading lines but you aren't sending lines. You need to add a \n at least to the end of the sent message.
You're reading infinitely and not checking for end of stream. The readLine() method returns null when the peer has disconnected. At the point you must exit the read loop and close the socket.
You're reading twice per iteration. That will attempt to read two separate lines from the input. It won't give you the same line twice. It seems pointless.

It's caused by the server or client close the connection when the other side haven't finish the IO operation. It'd better if you can paste the both main methods here. Then we can check it further

Related

Java server not working on windows server

I'm trying to connect to java server socket placed on windows server from my computer.
I always got a timeout exception.
I have tried to disable firewall with no luck. it still gave me the same error.
Exception in thread "main" java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
server code
public class Server implements Runnable {
public static int PORT = 3425;
private ServerSocket server;
public Server() throws IOException{
server = new ServerSocket(PORT);
}
#Override
public void run() {
try {
System.out.println("Waiting for connection");
Socket socket = server.accept();
System.out.println("new socket attached " + socket.toString());
System.out.println("waiting for message to read it");
DataInputStream input = new DataInputStream(socket.getInputStream());
byte [] bytes = new byte[1000];
int text = input.read(bytes);
System.out.println("message received");
System.out.println(text);
System.out.println(Arrays.toString(bytes));
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Client Code
public class Client implements Runnable {
Socket socket;
public Client() throws IOException {
System.out.println("trying to connect");
socket = new Socket("74.208.80.229", Server.PORT);
System.out.println("connected");
}
#Override
public void run() {
try {
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
Thread.sleep(1000);
System.out.println("message sent");
out.writeUTF("kasjdlkahdklajhdlkajsdhakljsdhlk");
out.flush();
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
} catch (InterruptedException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

ObjectOutputStream in client causes ServerException

I have a client-server application. Right now, I'm trying to test sending messages from the client to the server and then read them from the server. I'm using ObjectInputStream and ObjectOutputStream to transfer message objects between the client and server.
However, when I try to write an object from the client, it results in a SocketException.
Server code:
while (true) {
try {
log.trace("Waiting for connection.");
Socket clientSocket = socket.accept();
log.trace("Socket connected");
/* create thread */
new Thread(new RequestRunner(clientSocket, serverID)).start();
} catch (SocketTimeoutException e) {
log.trace("Socket timed out.");
socket.close();
break;
} catch (IOException e) {
log.error("Cannot accept connection...");
break;
}
}
Server Thread:
public class RequestRunner implements Runnable {
....
public RequestRunner(Socket socket, UUID serverID) {
client = socket;
this.serverID = serverID;
}
/**
* Start the thread for the request
*/
public void run() {
log.trace("Thread started for socket");
try {
out = new ObjectOutputStream(client.getOutputStream());
in = new ObjectInputStream(client.getInputStream());
} catch (IOException e) {
log.error("Cannot intialize streams...");
return;
}
while(client.isConnected()) {
/* initialize streams */
try {
/* read message */
Object obj = in.readObject(); // does not block
MessageFrame msg = (MessageFrame) obj;
processRequest(msg);
} catch (IOException e) {
; // triggers everytime
//log.error("IO error occured while trying to get input/output stream from socket");
} catch (ClassNotFoundException e) {
log.error("Cannot read MessageFrame");
}
}
}
}
Client code:
public void init(int port) throws IOException {
log.trace("intializing to port " + port);
clientID = UUID.randomUUID();
socket = new Socket("0.0.0.0",port);
out = new ObjectOutputStream(socket.getOutputStream());
in = new ObjectInputStream(socket.getInputStream());
}
public void sendEcho() throws Exception {
while(socket.isConnected()) {
try {
log.trace("Sending echo..");
msg = new EchoMessage(clientID);
curMsgID = msg.getMsgID();
out.writeObject(msg); // throws SocketException, socket closed
out.flush();
break;
} catch (SocketException e) {
log.error ("Cannot send echo.. socket closed.");
break;
} catch (IOException e) {
continue;
}
}
}
The statement out.writeObject(msg) causes a ServerSocket exception with Socket closed as the reason. And the server does not register receiving an object from in.readObject().
netstat shows the connection as established, the error occurs when I try to write the object.
What am I doing wrong ?
You should only have one InputStream and one OutputStream.
out = new ObjectOutputStream(client.getOutputStream());
in = new ObjectInputStream(client.getInputStream());
Should be:
out = client.getOutputStream();
in = client.getInputStream()
And you should change it in the client code when getting the streams from the sockets as well.

Keep communication open between server and client - Java

How do you make a client which is able to send a server multiple messages at anytime, and therefore a server listening for a message all the time.
Right now I have wrote some code which only allows me to send a message once. I thought this was due to me closing the input/output streams and the sockets. So I have been playing around for a while now and I can't seem to do it!
Client:
public class Client {
private Socket socket;
private OutputStream os;
public Client() {}
public void connectToServer(String host, int port) {
try {
socket = new Socket(host, port);
} catch (IOException e) {
e.printStackTrace();
}
sendMessage();
}
public void sendMessage() {
try {
os = socket.getOutputStream();
String string = "Anthony";
byte[] b = string.getBytes(Charset.forName("UTF-8"));
os.write(b);
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void STOP() {
stopOutput();
stopServer();
}
public void stopServer() {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void stopOutput() {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Server:
public class ConnectionHandler implements Runnable {
private Socket clientSocket;
private BufferedReader in;
public ConnectionHandler(Socket clientSocket) {
this.clientSocket = clientSocket;
String clientAddress = clientSocket.getInetAddress().toString()
.substring(1);
System.out.println("Connected to " + clientAddress);
try {
in = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
while (true) {
try {
ArrayList<String> data = new ArrayList<String>();
String inputLine;
while ((inputLine = in.readLine()) != null) {
data.add(inputLine);
}
if (data.size() > 0) {
System.out.println(data.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void STOP() {
stopInput();
stopConnection();
}
public void stopInput() {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void stopConnection() {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
At the moment on the client side, I send a message as soon as the socket is opened but after when I call the send function from another class it does not send...
How should I do this? Or what am I doing wrong?
Thanks in advance.
p.s. I am guessing client-server is the same as server-client, so if I know how to do one way I can easily switch it around... right?
Turns outs it was a simple error.
I as writing (sending-client) as an OutputStream however I was then reading (receiving-server) as BufferedReader! ha
So quick tip for anyone, make sure you receive messages the same way you send them!
Thanks for everyone who tried helping.
Your server is accepting data all the time, so you just have to save the OutputStream of you Client somewhere and write data to it every now and then. But do not close it, because then you close the Client socket, too.
After you have done that, you would need to change something else, because now your call of in.readLine() blocks your server, because it waits for the client to send something. To prevent that, you could try to add sending a String like "close" to the server when you want to close your client, something like that:
public void STOP() {
os.write("close".getBytes(Charset.forName("UTF-8")));
stopOutput();
stopServer();
}
and change the code in your server to
try {
ArrayList<String> data = new ArrayList<String>();
String inputLine;
while (!(inputLine = in.readLine()).equals("close")) {
data.add(inputLine);
}
if (data.size() > 0) {
System.out.println(data.toString());
}
} catch (IOException e) {
e.printStackTrace();
}

my chat server does not send messages to the client

i have this code to do chatting
but it did not work , but somebody told me that i should use byte array and a string but i did not understand i hope you can help me to fix this problem , this code belongs to the server...
public void run() {
try {
ServerSocket= new ServerSocket(44444);//inside there is the port mumber which will be gain later from firstscreen
ClientSocket= ServerSocket.accept();
OUT= new ObjectOutputStream(ClientSocket.getOutputStream());
IN=new ObjectInputStream(ClientSocket.getInputStream());
while (true){
Object input =IN.readObject();
textArea.setText(textArea.getText()+"Client:"+(String)input+"\n");//update the textarea
}//loop end
}catch (IOException e){
//joptionpane
e.printStackTrace();
} catch (ClassNotFoundException e) {
//joptionpane
e.printStackTrace();
}
}//end of try
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("Send")|| e.getSource() instanceof JTextField){
try {
if(textField.getText().isEmpty()) {
OUT.writeObject(textField.getText());
textArea.setText(textArea.getText()+"Assistant:"+textField.getText()+"\n");}
}
catch (IOException c){
c.printStackTrace();
}
}
I hope you understand that you are only letting just a SINGLE client connect to the server, since there cannot happen any other serverSocket.accept()
First, you are only sending the information if the textfield text is empty at if(textField.getText().isEmpty()) which is quite a nonsense, otherwise there is no call to send through socket any data.
Apart from this, I do not see the code for the actionPerformed block, which I assume you have coded it before with a JButton or so and implementing the jbutton.addActionListener()
Also, I hope ClientSocket is a class of your own, because a client is represented as a Socket, not ClientSocket.
On the other hand, I would suggest the following API writeUTF and forget about needing to cast the string into bytes or otherways, with the help of DataInput and DataOutputStreams.
The code would be left as:
public void run() {
try {
ServerSocket serverSocket= new ServerSocket(44444);//inside there is the port mumber which will be gain later from firstscreen
Socket clientSocket= serverSocket.accept();
DataOutputStream OUT = new DataOutputStream(clientSocket.getOutputStream());
DataInputStream IN = new DataInputStream(clientSocket.getInputStream());
while (true){
String input = IN.readUTF();
textArea.append(input+"\n"); //update the textarea
}//loop end
}catch (IOException e){
//joptionpane
e.printStackTrace();
} catch (ClassNotFoundException e) {
//joptionpane
e.printStackTrace();
}
}//end of try
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("Send")|| e.getSource() instanceof JTextField) {
try {
if(!textField.getText().isEmpty()) { //Do not forget to include the ! (NOT)
OUT.writeUTF(textField.getText());
textArea.setText(textArea.getText()+"Assistant:"+textField.getText()+"\n");
}
}
catch (IOException c){
c.printStackTrace();
}
}
}
I hope to have been able to have helped you.

Java - Listening to a socket with ObjectInputStream

Ok so , i have a thread class called 'Client' every time the server accepts a connection it creates a new Client....The run method listens for messages from the client and i am useing ObjectInputStream ..
do {
ObjectInputStream in = null;
try {
in = new ObjectInputStream(socket.getInputStream());
String message = (String) in.readObject();
System.out.println(message);
}
catch (ClassNotFoundException ex) {
isConnected = false;
System.out.println("Progoramming Error");
}
catch (IOException ex) {
isConnected = false;
System.out.println("Server ShutDown");
System.exit(0);
}
} while(isConnected);
The Problem i have is that why do i have to create a new ObjectInputStream every time it loops...and if i close the input stream at the end of the loop and it loops again for another message i will get a error...Please some one help
Only create the ObjectInputStream once (outside the loop) for a client connection, then put the readObject method into the loop.
Here's a working test class:
public class TestPrg {
public static void main(String... args) throws IOException {
ServerListener server = new ServerListener();
server.start();
Socket socketToServer = new Socket("localhost", 15000);
ObjectOutputStream outStream = new ObjectOutputStream(socketToServer.getOutputStream());
for (int i=1; i<10; i++) {
try {
Thread.sleep((long) (Math.random()*3000));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Sending object to server ...");
outStream.writeObject("test message #"+i);
}
System.exit(0);
}
static class ServerListener extends Thread {
private ServerSocket serverSocket;
ServerListener() throws IOException {
serverSocket = ServerSocketFactory.getDefault().createServerSocket(15000);
}
#Override
public void run() {
while (true) {
try {
final Socket socketToClient = serverSocket.accept();
ClientHandler clientHandler = new ClientHandler(socketToClient);
clientHandler.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
static class ClientHandler extends Thread{
private Socket socket;
ObjectInputStream inputStream;
ClientHandler(Socket socket) throws IOException {
this.socket = socket;
inputStream = new ObjectInputStream(socket.getInputStream());
}
#Override
public void run() {
while (true) {
try {
Object o = inputStream.readObject();
System.out.println("Read object: "+o);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
}
In this example Strings are sent trough the ObjectStream. If you get the ClassNotFoundException (http://download.oracle.com/javase/6/docs/api/java/io/ObjectInputStream.html#readObject()) and are using an independent client and server program than you might check if both the client and the server have the class of the object to send in their class paths.
The problem i personally had with Sockets and ObjectIOStream, is that it remembers all your object addresses, so each time you send and recive them on the client, if the address of sent object is not changed it will be copied from buffer. So
So
or create new objects each time you send them ( this is not a bad idiea, because ObjectIOStream seems to has limits on this buffer)
or use another Stream for these perpouse

Categories

Resources