前言:套接字(socket)编程能够实现服务器和客户端的通信,以下通过Socket编程结合多线程实现多人聊天室。
程序展示:
界面类
1.客户端界面 ClientView.java
public class ClientView extends JFrame implements ActionListener, KeyListener, Runnable {
private JTextArea textArea;
private JTextField textField, tfName;
private JButton btnSend, btnId;
private JLabel label;
private JPanel jp1, jp2;
public boolean isConnect = false;
private Socket socket = null;
private DataInputStream inputStream = null;
private DataOutputStream outputStream = null;
private JScrollPane scrollPane;
private static ClientView view;
public JTextArea getTextArea() {
return textArea;
}
public DataInputStream getInputStream() {
return inputStream;
}
public DataOutputStream getOutputStream() {
return outputStream;
}
public static void main(String[] args) {
view = new ClientView();
ServiceView.clientViews.add(view);
Thread thread = new Thread(view);
thread.start();
}
public ClientView() {
initView();
try {
socket = new Socket("localhost", 9090);//连接本地服务器
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void initView() {
textArea = new JTextArea(20, 20);
textArea.setEditable(false);
scrollPane = new JScrollPane(textArea);
textField = new JTextField(15);
textField.addKeyListener(this);
btnSend = new JButton(