Socket Reset Exception - Java - java

I am trying to send a ByteBuffer array over a socket on the port 25565 on the address "localhost". But for some reason, Java is throwing a connection reset exception when doing input.read(). Could someone please tell me whats going on?
Sender:
private static Socket socket;
public static void main(String[] args) throws IOException {
socket = new Socket("localhost", 25565);
String Password = "1234";
ByteBuffer Buffer = ByteBuffer.allocate(1 + Password.getBytes().length);
Buffer.put((byte) 0x00);
Buffer.putShort((short) Password.getBytes().length);
Buffer.put(Password.getBytes());
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
output.write(Buffer.array());
}
public static void sendBytes(byte[] myByteArray) throws IOException {
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
output.write("LOL".getBytes());
output.flush();
}
Receiver:
public static void main(String[] args) {
try {
ServerSocket ServerSocket = new ServerSocket(25565);
System.out.println("Waiting for connection...");
Socket socket = ServerSocket.accept();
DataInputStream Input = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
System.out.println(Input.read());
ServerSocket.close();
socket.close();
} catch (Exception e) {
if(e instanceof SocketTimeoutException) {
System.out.println("THE SOCKET TIMED OUT!");
}
else {
e.printStackTrace();
}
}
}
Stack trace:
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:189)
at java.net.SocketInputStream.read(SocketInputStream.java:121)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
at java.io.BufferedInputStream.read(BufferedInputStream.java:265)
at java.io.FilterInputStream.read(FilterInputStream.java:83)
at net.networking.Receiver.main(Receiver.java:17)
NOTE: Yes, I do know that just using input.read() will not get the whole ByteBuffer array I'm trying to send. But right now I just want to read the first byte and print it out to the console.

You're not closing the connection in the sender, so it gets reset when the process exits.
private static Socket socket;
public static void main(String[] args) throws IOException {
socket = new Socket("localhost", 25565);
String Password = "1234";
sendBytes(Password.getBytes());
output.close();
}
public static void sendBytes(byte[] myByteArray) throws IOException {
ByteBuffer Buffer = ByteBuffer.allocate(3 + myByteArray.length);
Buffer.put((byte) 0x00);
Buffer.putShort((short) myByteArray.length);
Buffer.put(myByteArray);
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
output.write(Buffer.array());
output.flush();
}
You're only reading one byte and then closing the connection. You need to read the entire transmission. If you close a socket with unread data still pending, the connection is reset. Also, if you want to handle exceptions separately, catch them separately. Don't use instanceof.
public static void main(String[] args) {
try {
ServerSocket ServerSocket = new ServerSocket(25565);
System.out.println("Waiting for connection...");
Socket socket = ServerSocket.accept();
DataInputStream Input = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
byte b = Input.readByte();
short dataLen = Input.readShort();
byte[] data = new byte[dataLen];
Input.readFully(data);
// use data as needed...
System.out.println("Data received");
Input.close();
ServerSocket.close();
} catch (SocketTimeoutException e) {
System.out.println("THE SOCKET TIMED OUT!");
} catch (Exception e) {
e.printStackTrace();
}
}

Related

how to send and receive data between client and server with JPOS?

i have an ISO8583 message to send between a client and a server (through sockets). What i did is declare socket and serverSockets classes, start server and accept connections, then create channel both on server and client to apply receive and send methods.
What i got is i cannot print the iso8583 message i send. here is the complete code :
The server's side code :
public class SocketServer {
private ServerSocket serverSocket;
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public void start(int port) throws IOException, ISOException {
serverSocket = new ServerSocket(port);
clientSocket = serverSocket.accept();
ISOChannel channel = new ASCIIChannel (
"localhost", 5000, new ISO87APackager() );
channel.connect();
ISOMsg r = channel.receive ();
System.out.println("isoMsg result "+r.getMTI());
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String data = in.readLine();
System.out.println("Inside Server Socket: " + data);
out.println("Data from server: " + data);
}
public void stop() throws IOException {
in.close();
out.close();
clientSocket.close();
serverSocket.close();
}
public static void main(String[] args) throws IOException, ISOException {
SocketServer server = new SocketServer();
server.start(5000);
System.out.println("Server start...");
}
}
and the client's code :
public class Client
{
public Client(String address, int port) throws ISOException
{
// establish a connection
try
{
Socket socket = new Socket(address, port);
System.out.println("Connected");
ISOChannel channel = new ASCIIChannel (
"localhost", 5000, new ISO87APackager() );
channel.connect();
ISOMsg r=new ISOMsg();
r.setMTI("0200");
channel.send(r);
InputStream in2= socket.getInputStream();
OutputStream out2=socket.getOutputStream();
String line = "";
try
{
in2.close();
out2.close();
socket.close();
}
catch(IOException i)
{
i.printStackTrace();
}
}catch(IOException e){
e.printStackTrace();
}
}
public static void main(String args[]) throws ISOException
{
Client client = new Client("localhost", 5000);
}
}

Java socket write issues

I am trying to create a Modbus setup as follows:
client <----> IED <----> Modbus Server
IED has the IP 192.168.x.x and Modbus Server uses localhost as IP. All entities are in the same VM. The client is supposed to send a request to the IED,the IED forwards it to the server and the server responds to the IED.
The problem is the IED receives the request from the master which is stored in a byte array but transmitting the request to the server does not work. Wireshark traces show that the TCP connection is established with the server but request is not transmitted.
See the code below:
public class App {
public static void main(String[] args) {
IEDServer iedServer = new IEDServer();
iedServer.start(502);
}
}
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
public class IEDServer {
private ServerSocket serverSocket;
public void start (int port){
try {
InetAddress inetAddress = InetAddress.getByName("192.168.20.138");
serverSocket = new ServerSocket(port, 1024, inetAddress);
while (true){
new ClientHandler(serverSocket.accept()).start();
System.out.println("Connection accepted");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void stop(){
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.*;
import java.net.Socket;
public class ClientHandler extends Thread{
private Socket clientSocket;
private DataOutputStream out;
private DataInputStream in;
public ClientHandler(Socket clientSocket) {
this.clientSocket = clientSocket;
}
#Override
public void run() {
try {
//connection from client
out = new DataOutputStream (clientSocket.getOutputStream());
in = new DataInputStream(clientSocket.getInputStream());
// in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// String readline;
//for connection to modbus server
Socket modbusSocket = new Socket("127.0.0.1",502);
modbusSocket.setSoTimeout(10000);
DataOutputStream modbus_out = new DataOutputStream (clientSocket.getOutputStream());
DataInputStream modbus_in = new DataInputStream(clientSocket.getInputStream());
byte [] modbus_bytes = {};
//read Modbus bytes from client to get client request
modbus_bytes = in.readAllBytes();
System.out.println("Modbus request: ");
for (byte b: modbus_bytes){
System.out.print(b);
}
System.out.println();
//transfer modbus request to modbus server
modbus_out.write(modbus_bytes, 0, modbus_bytes.length);
//get response from modbus server
modbus_bytes = modbus_in.readAllBytes();
System.out.println("Modbus response: ");
for (byte b: modbus_bytes){
System.out.print(b);
}
System.out.println();
//transfer response to client
out.write(modbus_bytes,0,modbus_bytes.length);
} catch (IOException e) {
e.printStackTrace();
}
//close TCP connection
try {
in.close();
out.close();
clientSocket.close();
System.out.println("Connection terminated");
} catch (IOException e) {
e.printStackTrace();
System.out.println("Connection termination failed");
}
}
}
Also find below, the wireshark screenshot
Call DataOutputStream.flush() after DataOutputStream.write() to force the bytes to be send
I managed to fix it. I mistakenly passed clientSocketinstead of modbusSocketas a parameter to the modbus_inand modbus_outStream instances. I also had to poll for availability of data before reading and then writing. Also, I noticed that the client-side closed the TCP session while the server-side had it open. So I ensured that the connection was closed after each query.
Please find modified code below for ClientHandler:
import java.io.*;
import java.net.Socket;
public class ClientHandler extends Thread {
private Socket clientSocket;
private Socket modbusSocket;
private DataOutputStream out, modbus_out;
private DataInputStream in, modbus_in;
public ClientHandler(Socket clientSocket) {
this.clientSocket = clientSocket;
System.out.println(clientSocket.getInetAddress());
try {
out = new DataOutputStream(new BufferedOutputStream(clientSocket.getOutputStream()));
in = new DataInputStream(new BufferedInputStream(clientSocket.getInputStream()));
// in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// String readline;
//for connection to modbus server
modbusSocket = new Socket("127.0.0.1", 502);
// modbusSocket.setSoTimeout(10000);
modbus_out = new DataOutputStream(new BufferedOutputStream(modbusSocket.getOutputStream()));
modbus_in = new DataInputStream(new BufferedInputStream(modbusSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
try {
//connection from client
if (in.available() > 0) {
//read Modbus bytes from client to get client request
System.out.println("===============Begin reading===============");
byte[] modbus_bytes = new byte[in.available()];
in.read(modbus_bytes);
System.out.println("Modbus request: ");
for (byte b : modbus_bytes) {
System.out.print(b);
}
System.out.println();
//transfer modbus request to modbus server
modbus_out.write(modbus_bytes);
modbus_out.flush();
System.out.println("Written to modbus server");
while (modbus_in.available() == 0) {
System.out.println("Waiting for device response...");
}
System.out.println("\nDevice response ready");
//get response from modbus server
modbus_bytes = new byte[modbus_in.available()];
modbus_in.read(modbus_bytes);
System.out.print("Modbus response: ");
for (byte b : modbus_bytes) {
System.out.print(b);
}
System.out.println("\nSending response to client");
//transfer response to client
out.write(modbus_bytes);
out.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
//close TCP connection
try {
// in.close();
// out.close();
clientSocket.close();
modbusSocket.close();
System.out.println("===========Connection terminated==============");
} catch (IOException e) {
e.printStackTrace();
System.out.println("Connection termination failed");
}
}
}

ObjectoutStram not set when trying to connect two client Socket to a server

I Have Class like below trying to connect two client socket to a server but when they get accepted by server I can only send data to the server through first socket (named s1 in code) and the second socket can do not send data to the server
public class Client_1 {
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
Socket s1 = new Socket("localhost", 8888);
Socket s2 = new Socket("localhost", 8888);
BufferedOutputStream bos1 = new BufferedOutputStream(s1.getOutputStream());
ObjectOutputStream oos1 = new ObjectOutputStream(bos1);
oos1.flush();
BufferedOutputStream bos2 = new BufferedOutputStream(s2.getOutputStream());
ObjectOutputStream oos2 = new ObjectOutputStream(bos2);
oos2.flush();
BufferedInputStream bis1 = new BufferedInputStream(s1.getInputStream());
ObjectInputStream ois1 = new ObjectInputStream(bis1);
BufferedInputStream bis2 = new BufferedInputStream(s2.getInputStream());
ObjectInputStream ois2 = new ObjectInputStream(bis2);
oos1.writeObject("a message from first client s1");
oos1.flush();
oos2.writeObject("a message from second client s2"); // sever does not receive this one
oos2.flush();
}
}
here is server code waiting for client
public class Main {
public static void main(String[] args) throws IOException {
WaitForClient();
}
public static void WaitForClient() throws IOException {
ServerSocket serverSocket = new ServerSocket(8888);
int i = 0;
while(true) {
Socket client = serverSocket.accept();
i++;
System.out.println(i + " client connected");
ClientThread clientThread = new ClientThread(client);
Thread thread = new Thread(clientThread);
thread.setDaemon(true);
thread.start();
}
}
and this is ClientThread who get info from socket
public class ClientThread implements Runnable {
Socket clientSocket;
ObjectInputStream oIStream;
ObjectOutputStream oOStream;
Object inputObject;
BufferedInputStream bIS;
BufferedOutputStream bOS;
public ClientThread(Socket clientSocket) {
this.clientSocket = clientSocket;
}
#Override
public void run() {
try {
bOS = new BufferedOutputStream(clientSocket.getOutputStream());
bIS = new BufferedInputStream(clientSocket.getInputStream());
oOStream = new ObjectOutputStream(bOS);
oOStream.flush();
oIStream = new ObjectInputStream(bIS);
while (clientSocket.isConnected()) {
if (bIS.available() > 0) {
inputObject = oIStream.readObject();
doService(inputObject);
System.out.println(inputObject.toString());
inputObject = null;
}
}
System.out.println("connection is closed!!!");
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
System.out.println("socket exception" + e.getMessage());
}
}
}
and this is what printed to console
1 client connected
2 client connected
a message from first client s1 // input from the first socket but nothing from the second socket
This code should work,Are you getting any error in doService method?. In case any exception while loop will break and print statement will not be executed. Otherwise it should print data from both client

Why is my message sent only once in Java socket server?

there is a server that is considered to server multiple clients at the same time.
So when clients connects, he is added to clients array. And when server gets the message, it is sent to all the clients.
It works perfectly when one client is connected, but when I have 2 clients at the same time, the message is sent only once, it doesn't work anymore after that. What's the problem?
Server
static DataInputStream inputStream;
static DataOutputStream outputStream;
static ServerSocket serverSocket;
static final int PORT = 3003;
static Socket someClient;
static List<Socket> clients = new ArrayList<>();
public Server()
{
start();
}
public static void main(String[] args) throws IOException
{
try{
serverSocket = new ServerSocket(PORT);
print("Server started on " + serverSocket.getInetAddress().getHostAddress());
while (true)
{
someClient = serverSocket.accept();
new Server();
}
} catch (Exception e){
e.printStackTrace();
}
}
#Override
public void run()
{
try{
clients.add(someClient);
print("Connected from " + someClient.getInetAddress().getHostAddress());
InputStream sin = someClient.getInputStream();
OutputStream sout = someClient.getOutputStream();
inputStream = new DataInputStream(sin);
outputStream = new DataOutputStream(sout);
String message;
while (true)
{
message = inputStream.readUTF();
print(message);
for (int i = 0; i < clients.size(); i++)
{
Socket client = clients.get(i);
OutputStream os = client.getOutputStream();
DataOutputStream oss = new DataOutputStream(os);
oss.writeUTF(message);
}
}
} catch (Exception e){
e.printStackTrace();
}
}
Client
socket = new Socket("0.0.0.0", 3003);
InputStream sin = socket.getInputStream();
OutputStream sout = socket.getOutputStream();
inputStream = new DataInputStream(sin);
outputStream = new DataOutputStream(sout);
sendButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(key != null && key.length() == 16)
{
Date date = new Date();
String msg = ">> " + nickname + ": " + messageField.getText()+" | " + date.getHours()+":"+date.getMinutes()+"\n";
try {
outputStream.writeUTF(Encrypt.AESEncrypt(key, msg));
} catch (IOException e1) {
e1.printStackTrace();
}
messageField.setText("");
}
else if(key == null)
JOptionPane.showMessageDialog(J_Frame, "Your key field is empty");
else if(key.length() != 16)
JOptionPane.showMessageDialog(J_Frame, "Key's length should be 16 symbols");
}
});
while (true)
{
String message;
message = inputStream.readUTF();
append("\n" + Encrypt.AESDecrypt(key, message));
}
} catch (Exception e1) {
clear();
append(">> Unable to connect to the server.");
hideButtons();
}
Every time a client connects to your server, it replaces the previous connection:
while (true)
{
someClient = serverSocket.accept();
...
}
someClient is static:
static Socket someClient;
which means it is shared by all threads.
Also, access to it is not synchronized in any way, which means changes to its value are not guaranteed to be visible to other threads.
As Peter Lawrey pointed out in the comments, the streams also need to be non-static:
static DataInputStream inputStream;
static DataOutputStream outputStream;
actually, the fact that you are always reading from the "latest" inputStream may be the main cause of the behavior you are describing.
outputStream seems to be unused, so it might be best to remove it.
In addition to that, OutputStreams may need to be flushed in order to actually send data.

How to stop DataInputStream get byte[]?

I want to read and write byte[] data with a socket, but I cannot stop the stream.
This is my server:
public class Server {
public static void main(String[] args) throws IOException {
System.out.println("Welcome to Server side");
DataInputStream in;
DataOutputStream out;
ServerSocket servers = null;
Socket fromclient = null;
// create server socket
try {
servers = new ServerSocket(4444);
} catch (IOException e) {
System.out.println("Couldn't listen to port 4444");
System.exit(-1);
}
try {
System.out.print("Waiting for a client...");
fromclient = servers.accept();
System.out.println("Client connected");
} catch (IOException e) {
System.out.println("Can't accept");
System.exit(-1);
}
in = new DataInputStream(fromclient.getInputStream());
out = new DataOutputStream(fromclient.getOutputStream());
String input = "", output;
System.out.println("Wait for messages");
byte[] bytes = new byte[16*1024];
int count;
while ((count = in.read(bytes)) > 0) {
byte[] mass = "some data".getBytes("UTF-8");
out.write(mass, 0, count);
System.out.println(Arrays.toString(bytes));
}
out.close();
in.close();
fromclient.close();
servers.close();
}
}
When I receive data from the client it opens an infinite stream which doesn't stop.
How can I stop this DataInputStream?
Close the connection from the client side (or server side). As long as the connection is open, the server will wait for data to be sent.
In a proper setup you would have a well defined protocol, which could then include shutdown messages to inform the server when the client decides to disconnect. Simply closing the connection is a "raw" way to achieve that, but it's not very elegant.

Categories

Resources