我试图使用Java套接字制作一个简单的聊天应用程序,下面是服务器的代码:
public ServerSocket ss;
public ArrayList<Client> Clients = new ArrayList<Client>();
String Alphabets = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789";
public Server() throws IOException
{
ss = new ServerSocket(1111);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(null);
this.setResizable(false);
this.setSize(400,150);
this.getContentPane().setBackground(Color.BLACK);
this.setTitle("Server");
JLabel label = new JLabel("Server Running");
label.setForeground(Color.WHITE);
label.setBounds(15,25,350,60);
label.setFont(new Font(Font.SANS_SERIF,Font.PLAIN,50));
this.add(label);
this.setVisible(true);
while(true)
{
Socket socket = ss.accept();
DataOutputStream dout = new DataOutputStream(socket.getOutputStream());
String id = getId();
dout.writeUTF(id);
Client c = new Client(socket,id);
dout.close();
dout.flush();
}
}
String getId()
{
Random rand = new Random();
String id = "";
for(int i = 0;i < 6;i++)
{
char i3 = Alphabets.charAt(rand.nextInt(0,Alphabets.length()));
id += i3;
}
return id;
}
一切正常,当客户端连接时,他获得一个id并被添加到Clients
--这里是客户机连接的代码:
public String Connect() throws UnknownHostException, IOException
{
mySocket = new Socket("localhost",1111);
DataInputStream din = new DataInputStream(mySocket.getInputStream());
String id = din.readUTF();
return id;
}
问题是,我得到了异常java.net.SocketException:当我向服务器发送输入时,主机中的软件中止了一个已建立的连接,它不会在第一次按send时发送,下一次按下send就会发出这个异常,下面是发送输入的代码:
public void SendMessage(String msg) throws IOException
{
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
dout.writeUTF(msg);
AddToMessages(Id + ": " + msg);
}
如果有人帮忙,我会很高兴的,因为我已经研究这个问题很长时间了,而且似乎没有人提出这个问题。
发布于 2022-10-27 07:06:59
嗯,我发现重新启动你的电脑解决了问题,这是有点奇怪,但它的工作!
https://stackoverflow.com/questions/74162379
复制相似问题