当前位置: 代码迷 >> J2SE >> java socket 调用readline()方法的有关问题
  详细解决方案

java socket 调用readline()方法的有关问题

热度:42   发布时间:2016-04-23 20:33:23.0
java socket 调用readline()方法的问题
public class ChatRoomClient {
JTextArea jta;
JTextField jtf;
BufferedReader in;
PrintWriter out;
    JButton btn;                 

private void initGui() {



JFrame f = new JFrame("Client");                  
f.setSize(500, 300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   

JPanel p1=new JPanel();
p1.add(new JButton("聊天记录"));

f.add(p1,"East");


jta = new JTextArea();
jta.setEditable(false);
f.add(new JScrollPane(jta));
jtf = new JTextField();
f.add(jtf, "South" +"");
f.setVisible(true);
jtf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String text = jtf.getText();
//jtf.setText("");
//out.println(text);
//out.flush();
}
});
}

private void initNet() {
try {
Socket s = new Socket("127.0.0.1", 9000);
out = new PrintWriter(s.getOutputStream());         //大概是这里  换行符怎么添加
in = new BufferedReader(new InputStreamReader(s.getInputStream()));
} catch (Exception e) {
e.printStackTrace();
}
}

public void receive() {
try {
while (true) {
String str = in.readLine();
if (str == null)
return;
jta.append(str + "\n");
}
} catch (IOException e) {
}
}

public ChatRoomClient() {
initGui();
initNet();
}

public static void main(String[] args) throws Exception {

ChatRoomClient c = new ChatRoomClient();
c.receive();
}
}



下面是服务器端的
public class ChatRoomServer {
public static void main(String[] args) throws Exception {
List sockets = new ArrayList();
ServerSocket ss = new ServerSocket(9000);
while (true) {
Socket s = ss.accept();
sockets.add(s);
Thread t = new ChatThread(s, sockets);
t.start();
}
}
}

class ChatThread extends Thread {
Socket s;
List sockets;

public ChatThread(Socket s, List sockets) {
this.s = s;
this.sockets = sockets;

}

public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(s
.getInputStream()));
///////////////////////////////
while (true) {
String str = in.readLine();  
if (str == null)
return;
for (int i = 0; i < sockets.size(); i++) {
Socket s2 = (Socket) sockets.get(i);
PrintWriter out = new PrintWriter(s2.getOutputStream());
out.println(str);
out.flush();
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////
} catch (IOException e) {
} finally {
sockets.remove(s);
try {
s.close();
} catch (IOException e) {
}
}
}
}



在界面登录成功后  总是程序没有反映  
------解决方案--------------------
报什么错误呢???写点注释别人才会更积极的解答你的问题!
------解决方案--------------------
目测程序没问题,可以聊天 。但下面的注释必须去掉。那是聊天发送的触发代码,你注释了还聊啥
 jtf.addActionListener(new ActionListener() {   
          public void actionPerformed(ActionEvent arg0) {    
             String text = jtf.getText();       
          //jtf.setText("");          
       //out.println(text);       
          //out.flush();   
          }       
  }); 
  相关解决方案