当前位置: 代码迷 >> J2SE >> 实现个简单的聊天室,该怎么解决
  详细解决方案

实现个简单的聊天室,该怎么解决

热度:213   发布时间:2016-04-24 15:26:11.0
实现个简单的聊天室
主要的功能服务器端和客户端,服务器一开,客户端之间就可以相互通信,
知道大体的思路,客户端的界面已经写好,大家帮帮我
客户端的界面
import   java.awt.event.*;
import   javax.swing.*;
public   class   ChatClient   {
public   static   void   main(String[]   args)   {
JFrame   frame=new   JFrame( "Chat   Client ");
frame.setSize(400,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

final   JTextArea   jta=new   JTextArea();
final   JTextField   jtf=new   JTextField();
frame.add(new   JScrollPane(jta));
frame.add(jtf, "South ");

jta.setEditable(false);

frame.setVisible(true);

jtf.addActionListener(new   ActionListener(){
public   void   actionPerformed(ActionEvent   arg0)   {
String   text=jtf.getText();
jtf.setText( " ");
jta.append(text+ "\n ");
}
});
}
}


------解决方案--------------------
这个程序有点小问题,测试了就知道了
//客户端
package chat;

import java.awt.event.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.*;

public class ChatClient {
public static void main(String[] args) {
JFrame frame = new JFrame( "Chat Client ");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

final JTextArea jta = new JTextArea();
final JTextField jtf = new JTextField();
frame.add(new JScrollPane(jta));
frame.add(jtf, "South ");

jta.setEditable(false);

frame.setVisible(true);

class ClientThread extends Thread {
public void run() {
Socket s = null;
try {
s = new Socket( "127.0.0.1 ", 9000);

InputStream is = s.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);

while (true) {
String str = br.readLine();
jta.append(str + "\n ");
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (s != null)
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Thread t = new ClientThread();
t.start();

class WriterClient extends Thread {
public void run() {
Socket s = null;
try {
s = new Socket( "127.0.0.1 ", 9000);

OutputStream os = s.getOutputStream();
PrintWriter pw = new PrintWriter(os);

pw.println(jtf.getText());

pw.flush();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (s != null)
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

jtf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Thread t1 = new WriterClient();
t1.start();
}
});
  相关解决方案