所以我仍在尝试解决这个客户端/服务器概念。除了出现此错误外,我终于有了一个可以正常工作的程序。我环顾了整个网络,看看我是否可以尝试自己解决这个问题,但对于我的生活,我无法弄清楚。有人可以看看客户端代码,看看我在哪里犯了错误并指出正确的方向。
java.net.SocketException: Socket closed
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
at java.net.SocketInputStream.read(SocketInputStream.java:170)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:161)
at java.io.BufferedReader.readLine(BufferedReader.java:324)
at java.io.BufferedReader.readLine(BufferedReader.java:389)
at Contact$IncomingReader.run(Contact.java:104)
at java.lang.Thread.run(Thread.java:745)
客户代码
public class Contact{
JTextArea incoming;
JTextField outgoing;
BufferedReader reader;
PrintWriter writer;
Socket sock;
JPanel mainP;
JScrollPane scroll;
JButton sendB;
public static void main(String[] args){
Contact client = new Contact();
client.go();
}
public void go(){
JFrame frame = new JFrame("Client");
mainP = new JPanel();
incoming = new JTextArea(15,50);
incoming.setLineWrap(true);
incoming.setWrapStyleWord(false);
incoming.setEditable(false);
scroll = new JScrollPane(incoming);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
outgoing = new JTextField(20);
sendB = new JButton("Send");
sendB.addActionListener(new SendButtonListener());
mainP.add(scroll);
mainP.add(outgoing);
mainP.add(sendB);
Networking();
Thread readerThread = new Thread(new IncomingReader());
readerThread.start();
frame.setLocationRelativeTo(null);
frame.getContentPane().add(BorderLayout.CENTER, mainP);
frame.setSize(400,400);
frame.setVisible(true);
}
private void Networking(){
try{
sock = new Socket("127.0.0.1",5000);
InputStreamReader streamReader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(streamReader);
writer = new PrintWriter(sock.getOutputStream());
System.out.println("Connection Established");
}catch(IOException ex){
ex.printStackTrace();
}
}
public class SendButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
try{
writer.println(outgoing.getText());
writer.close();
}catch(Exception ex){
ex.printStackTrace();
}
outgoing.setText("");
outgoing.requestFocus();
}
}
public class IncomingReader implements Runnable{
@Override
public void run() {
String message;
try{
while((message = reader.readLine()) != null){
System.out.println("read " + message);
incoming.append(message + "\n");
}
}catch(Exception ex){
ex.printStackTrace();
}
}
}
}
这个异常的意思是你关闭socket然后继续使用
writer.close();
你在这里关闭了它。关闭套接字的输入流或输出流都会关闭套接字。请参阅 Javadoc。