我正在嘗試使用 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: An established connection was aborted by the software in your host machine as I send input to server, it doesn't send the first time I press send, and next time I按發送它給出這個例外,這里是發送輸入的代碼:
public void SendMessage(String msg) throws IOException
{
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
dout.writeUTF(msg);
AddToMessages(Id ": " msg);
}
如果有人提供幫助,我會非常高興,因為我已經研究這個問題很長時間了,但似乎沒有人提出來。
uj5u.com熱心網友回復:
好吧,我發現重新啟動您的電腦可以解決問題,這有點奇怪,但它有效!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/521418.html
標籤:爪哇插座例外联网
