Answer the question
In order to leave comments, you need to log in
How to correctly transfer objects from client to server via Socket(SocketException: connection reset)?
Good day to all! I practice transferring data over sockets from the client to the server and vice versa, in the case of transferring text through the PrintWriter, everything works fine, but as soon as I try to transfer objects through the ObjectOutputStream, the server throws a SocketException: connection reset.
Essence: the client connects to the server and sends him a message - an object containing the name of the sender and his ID. The server accepts this object and prints the name and ID of the sender to the console.
package objectschange;
import java.io.*;
import java.net.*;
public class ServerSide {
protected ObjectInputStream serverOIS;
public static void main(String[] args) {
ServerSide server = new ServerSide();
server.launchServer();
}
private void launchServer() {
try {
ServerSocket srvSocket = new ServerSocket(3200);
while (true) {
Socket serverClientSocket = srvSocket.accept();
serverOIS = new ObjectInputStream(serverClientSocket.getInputStream());
handleObject(serverOIS);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void handleObject(ObjectInputStream serverOIStream) {
ClientMessagePackage messagePackage;
try {
while ((messagePackage = (ClientMessagePackage) serverOIStream.readObject()) != null) {
System.out.println(messagePackage.packageSender + " " + messagePackage.packageSenderID);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
package objectschange;
import java.io.*;
import java.net.*;
public class ClientSide {
protected ObjectOutputStream clientOOS;
public static void main(String[] args) {
ClientSide client = new ClientSide();
client.establishConnection();
}
private void establishConnection() {
try {
Socket clientSocket = new Socket("127.0.0.1", 3200);
Thread.sleep(3000);
clientOOS = new ObjectOutputStream(clientSocket.getOutputStream());
sendPackage(clientOOS, new ClientMessagePackage("Name", 1));
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void sendPackage(ObjectOutputStream clientOOStream, ClientMessagePackage clientMPackage) {
try {
clientOOStream.writeObject(clientMPackage);
clientOOStream.flush();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
class ClientMessagePackage implements Serializable {
protected String packageSender;
protected int packageSenderID;
protected ClientMessagePackage(String name, int id) {
packageSender = name;
packageSenderID = id;
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question