gpt4 book ai didi

java DataOutputStream异常

转载 作者:行者123 更新时间:2023-11-29 08:17:47 25 4
gpt4 key购买 nike

在我第二次键入内容时(在我键入主机名之后)在第 24 行抛出异常 - 服务器工作正常。代码

import java.io.*;
import java.net.*;

class TCPclient {
public static void main(String[] args) throws Exception {
String hostname, msg;
InetAddress hostaddress;
BufferedReader inFromUser = new BufferedReader (new InputStreamReader(System.in));
System.out.println("Please type host\n");
hostname = inFromUser.readLine(); //I type localhost
hostaddress = InetAddress.getByName(hostname);
Socket cSocket = new Socket(hostaddress, 44444);
String cAddress = cSocket.getLocalSocketAddress().toString();
DataOutputStream outToServer = new DataOutputStream (cSocket.getOutputStream());
while (true)
{
msg = inFromUser.readLine();
System.out.println(msg);
if (msg.equals("exit"))
{
System.out.println("exit");
break;
}
outToServer.writeBytes(cAddress + " said : " + msg + '\n'); //this line throws an exception the second time it runs
}
cSocket.close();
}
}

我是 Java 的新手,所以我想我遗漏了一些明显的东西。异常读取:

Exception in thread "main" java.net.SocketException: Software caused connection abort: socket write error at java.net.SocketOutputStream.socketWrite0(Native Method) at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92) at java.net.SocketOutputStream.write(SocketOutputStream.java:115) at java.io.DataOutputStream.writeBytes(DataOutputStream.java:259) at TCPclient.main(TCPClient.java:52) Java Result: 1

服务器:

import java.io.*;
import java.net.*;

class TCPServer {
public static void main(String argv[]) throws Exception {
String clientSentence;
ServerSocket welcomeSocket = new ServerSocket(44444);
while(true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(connectionSocket.getInputStream( ) ) );
clientSentence = inFromClient.readLine();
System.out.println(clientSentence + "\n");
}
}
}

最佳答案

您的客户端创建一个套接字并一遍又一遍地写入该套接字。另一方面,您的服务器执行以下操作:

ServerSocket welcomeSocket = new ServerSocket(44444);
while(true) {
Socket connectionSocket = welcomeSocket.accept();

接受传入的连接,读取一行,然后放弃它(我猜在垃圾收集时套接字的最终确定会关闭连接)。然后等待新的连接。

所以要解决您眼前的问题,请尝试移动

    Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(connectionSocket.getInputStream( ) ) );

在 while 循环之前。

关于java DataOutputStream异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3151527/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com