问题描述
服务端程序是这样的:importjava.net.*;importjava.awt.*;importjava.awt.event.*;importjava.io.*;importjavax.swing.*;publicclassserverTwoextendsJFrameimplementsActionListener,Runnable{//声明数据通信类对象和窗体组件对象InetAddressaddr;ServerSocketse;Socketso;DataInputStreamin;DataOutputStreamout;JButtonbtn;JTextFieldjtf;JTextAreajta;JScrollPanejsp;serverTwo()throwsException{//构建可视化窗体btn=newJButton("发送");jtf=newJTextField(15);btn.addActionListener(this);this.setLayout(newBorderLayout());jta=newJTextArea();JPaneljp=newJPanel();jp.add(btn);jp.add(jtf);//创建滚动条面板jsp=newJScrollPane();jsp.setViewportView(jta);this.setTitle("Server");this.add(BorderLayout.SOUTH,jp);this.add(jsp);this.setSize(300,200);this.setVisible(true);//创建ServerSocket,并开始监听addr=InetAddress.getByName("aci");se=newServerSocket(135);System.out.println("服务器启动...");so=se.accept();System.out.println("有客户端连接...");//创建数据流in=newDataInputStream(so.getInputStream());out=newDataOutputStream(so.getOutputStream());}publicvoidrun(){//接收客户端的消息try{while(true){jta.append("client:"+in.readUTF());jta.append("n");}}catch(Exceptionex){System.out.println(ex.getMessage());}}publicstaticvoidmain(String[]args)throwsException{//将当前类作为线程启动Threadt=newThread(newserverTwo());t.start();}publicvoidactionPerformed(ActionEvente){try{//向客户端发送消息out.writeUTF(jtf.getText());out.flush();//发送一次消息,在当前窗体也显示自身的消息jta.append("me:"+jtf.getText());jta.append("n");}catch(Exceptionex){System.out.println(ex.getMessage());}}}客户端是这样的:importjava.net.*;importjava.io.*;importjava.awt.*;importjava.awt.event.*;importjavax.swing.*;publicclassclientTwoextendsJFrameimplementsActionListener,Runnable{Socketso;DataInputStreamin;DataOutputStreamout;JButtonbtn;JTextFieldjtf;JTextAreajta;JScrollPanejsp;clientTwo()throwsException{btn=newJButton("发送");jtf=newJTextField(15);btn.addActionListener(this);this.setLayout(newBorderLayout());jta=newJTextArea();JPaneljp=newJPanel();jp.add(btn);jp.add(jtf);jsp=newJScrollPane();jsp.setViewportView(jta);this.setTitle("Client");this.add(BorderLayout.SOUTH,jp);this.add(jsp);this.setSize(300,200);this.setVisible(true);//创建客户端Socket并创建输入输出流so=newSocket("localhost",135);in=newDataInputStream(so.getInputStream());out=newDataOutputStream(so.getOutputStream());}publicvoidrun(){//接收服务器返回的消息try{while(true){jta.append("server:"+in.readUTF());jta.append("n");}}catch(Exceptionex){System.out.println(ex.getMessage());}}publicstaticvoidmain(String[]args)throwsException{Threadt=newThread(newclientTwo());t.start();}publicvoidactionPerformed(ActionEvente){try{//向服务器发送消息out.writeUTF(jtf.getText());out.flush();jta.append("me:"+jtf.getText());jta.append("n");}catch(Exceptionex){System.out.println(ex.getMessage());}}}运行时,客户端可以,服务端运行时,不能在jta中显示jtf中输入的信息,控制台只是输出一个null
解决方案
解决方案二:
把addr=InetAddress.getByName("aci");这行代码给注释掉吧,然后就可以了,我已经试过了
解决方案三:
//创建数据流in=newDataInputStream(so.getInputStream());out=newDataOutputStream(so.getOutputStream());server端的数据流不是这样创建的