我想做的事
客户端/服务器应用程序:
客户端打开一个带有按钮的GUI" Read"。
单击它将打开一个新框架,其中包含一些要阅读的文章。在这个阶段短String
。
摘要:
我尝试了什么
在目前的发展阶段,我一直坚持这个错误信息:
Exception in thread "main" java.net.SocketException: Software caused connection abort: socket write error
这是服务器级:
public class StartServer {
public static void main(String[] argv) throws Exception {
@
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("Server started");
while (true) {
List<String> receive = new ArrayList<String>();
// Wait for client to connect
Socket aNewClientSocket = serverSocket.accept();
System.out.println("Server-Client connexion established!!");
ObjectInputStream toReceiveFromClient = new ObjectInputStream(aNewClientSocket.getInputStream());
receive = (List<String>) toReceiveFromClient.readObject();
System.out.println(aNewClientSocket.getLocalPort());
System.out.println(aNewClientSocket.getInetAddress());
switch (receive.get(0)) {
case "Reader button click":
List<Object> toSend = new ArrayList<Object>();
Article a=new Article();
a.setTitle("New Title");
toSend.add(a);
ObjectOutputStream objectWayToSend = new ObjectOutputStream(aNewClientSocket.getOutputStream());
objectWayToSend.writeObject(toSend);
objectWayToSend.flush();
default:
throw new IllegalArgumentException("Bad request from client!!");
}
客户相关方法:
public void sendToServer(List<String> toSend) throws UnknownHostException, IOException {
try {
Socket socket = new Socket("localhost", 9999);
ObjectOutputStream objectWayToSend = new ObjectOutputStream(socket.getOutputStream());
objectWayToSend.writeObject(toSend);
objectWayToSend.flush();
objectWayToSend.close();
}
catch(Exception e) {
JOptionPane.showMessageDialog(frame, "The server is offline or connection can't be establish!");
}
}
@SuppressWarnings("unchecked")
public List<Object> receiveFromServer() throws UnknownHostException, IOException {
List<Object> receive = new ArrayList<Object>();
try {
Socket socket = new Socket("localhost", 9999);
ObjectInputStream objectToGet = new ObjectInputStream(socket.getInputStream());
receive=(List<Object>) objectToGet.readObject();
}
catch(Exception e) {
JOptionPane.showMessageDialog(frame, "The server is offline or connection can't be establish!");
}
return receive;
GUI中引用的按钮
btnCiteste = new JButton("Read");
btnCiteste.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
List<String> toSend = new ArrayList<String>();
toSend.add("Read");
try {
sendToServer(toSend);
List<Object> received= receiveFromServer();
//new ArticoleReaderFrame ();
} catch (IOException e) {
e.printStackTrace();
}
}
});
答案 0 :(得分:1)
在完成发送后但在开始接收之前关闭客户端中的OutputStream
。这就是问题的原因,因为关闭OutputStream
也会关闭底层的Socket。
引用Official reasons for “Software caused connection abort: socket write error”