不多哔哔,就是JAVA网络编程内容,一个多线程聊天室包含了所有内容。
服务端
import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ServerTPC extends JFrame {
private JTextField enterField;
private JTextArea displayArea;
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;
private JButton but;
private JPanel panel;
public ServerTPC() {
super("管理员");
panel = new JPanel(new FlowLayout());
but = new JButton("发送");
Container container = getContentPane();
enterField = new JTextField(20);
enterField.setEditable(false);
enterField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sendData(e.getActionCommand());
enterField.setText("");
}
});
but.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sendData(e.getActionCommand());
enterField.setText("");
}
});
try {
server = new ServerSocket(8080);
} catch (IOException e1) {
JOptionPane.showMessageDialog(null, "端口被占用请 重新选择", "提示", JOptionPane.INFORMATION_MESSAGE);
}
panel.add(enterField);
panel.add(but);
container.add(panel, BorderLayout.SOUTH);
displayArea = new JTextArea();
displayArea.setEditable(false);
container.add(new JScrollPane(displayArea), BorderLayout.CENTER);
setBounds(600, 200, 500, 250);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Thread a = new Thread(new Roll());
a.start();
}
class Roll implements Runnable {
public void run() {
try {
while (true) {
try {
waitForConnection();
getStreams();
processConnection();
} catch (EOFException e) {
System.out.println("这里发生了错误请及时修复");
} finally {
closeConnection();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void waitForConnection() throws IOException {
displayMessage("等待用户接入");
connection = server.accept();
}
private void getStreams() throws IOException {
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
}
private void processConnection() throws IOException {
String message = "连接成功";
sendData(message);
setTextFieldEditable(true);
try {
do {
message = (String) input.readObject();
displayMessage("\n" + message);
} while (true);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "好友已下线", "提示", JOptionPane.INFORMATION_MESSAGE);
}
}
private void closeConnection() {
displayMessage("对话结束\n");
setTextFieldEditable(false);
try {
output.close();
input.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private void sendData(String message) {
try {
Date date = new Date();
SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
output.writeObject("管理员:" + sf.format(date) + "\n" + message);
output.flush();
displayMessage("\n管理员:" + sf.format(date) + "\n" + message);
} catch (Exception e) {
displayArea.append("\n发生错误");
}
}
private void displayMessage(final String messageToDisplay) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
displayArea.append(messageToDisplay);
displayArea.setCaretPosition(displayArea.getText().length());
}
});
}
private void setTextFieldEditable(final boolean editable) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
enterField.setEditable(editable);
}
});
}
public static void main(String[] args) {
ServerTPC a = new ServerTPC();
}
}
客户端
import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ClientTPC extends JFrame{
private JTextField enterField;
private JTextArea displayArea;
private ObjectOutputStream output;
private ObjectInputStream input;
private String message="";
private String chatServer,userName;
private Socket client;
private JButton but;
private JPanel panel;
private int server;
public ClientTPC() {
super("客户");but=new JButton("发送");
panel=new JPanel(new FlowLayout());
chatServer="127.0.0.1"; //ip
server=8080; //端口
userName="燕双嘤";
Container c=getContentPane();
enterField=new JTextField(20);
enterField.setEditable(false);
enterField.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
sendData(e.getActionCommand());
enterField.setText( "" );
}
});
panel.add(enterField);
panel.add(but);
c.add(panel,BorderLayout.SOUTH);
displayArea=new JTextArea();
displayArea.setEditable(false);
c.add(new JScrollPane(displayArea),BorderLayout.CENTER);
setBounds(600, 200, 500, 250);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Thread a=new Thread(new Roll());
a.start();
}
class Roll implements Runnable{
public void run() {
try {
connectionToServer();
getStreams();
processConnection();
} catch (EOFException e1) {
System.out.println("客户断开连接");
} catch(IOException e2) {
e2.printStackTrace();
} finally {
closeConnection();
}
}
}
private void connectionToServer() throws IOException{
displayMessage("尝试连接");
client=new Socket(chatServer,server);
}
private void getStreams() throws IOException{
output=new ObjectOutputStream(client.getOutputStream());
output.flush();
input=new ObjectInputStream(client.getInputStream());
}
private void processConnection()throws IOException{
setTextFieldEditable(true);
try {do {
message=(String)input.readObject();
displayMessage("\n"+message);
} while (true);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "服务器已关闭", "提示", JOptionPane.INFORMATION_MESSAGE);
}
}
private void closeConnection() {
displayMessage("\n断开连接");
setTextFieldEditable(false);
try {
output.close();
input.close();
client.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private void sendData(String message) {
try {
Date date = new Date();
SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
output.writeObject(userName+":"+sf.format(date)+"\n"+message);
output.flush();
displayMessage("\n"+userName+":"+sf.format(date)+"\n"+message);
} catch (Exception e) {
displayArea.append("\n发生了错误");
}
}
private void displayMessage(final String messageToDisplay) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
displayArea.append(messageToDisplay);
displayArea.setCaretPosition(displayArea.getText().length());
}
});
}
private void setTextFieldEditable(final boolean editable) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
enterField.setEditable(editable);
}
});
}
public static void main(String[] args) {
ClientTPC a =new ClientTPC();
}
}
服务端
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.JOptionPane;
public class Server {
private ServerSocket serverSocket;
private HashSet allSockets;
public Server() {
try {
serverSocket = new ServerSocket(8080);
JOptionPane.showMessageDialog(null, "服务器已启动\n请运行客户端", "提示", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception e) {
e.printStackTrace();
}
allSockets = new HashSet();
try {
startService();
} catch (IOException e) {
System.out.println("错误");
}
}
public void startService() throws IOException {
while (true) {
Socket s = serverSocket.accept();
System.out.println("用户已进入聊天室");
allSockets.add(s);
new ServerThread(s).start();
}
}
private class ServerThread extends Thread {
Socket socket;
public ServerThread(Socket socket) {
this.socket = socket;
}
public void run() {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (true) {
String str = br.readLine();
sendMessageTOAllClient(str);
}
} catch (Exception e) {
System.out.println("用户退出聊天室");
}
}
public void sendMessageTOAllClient(String message) throws IOException {
for (Socket s : allSockets) {
PrintWriter pw = new PrintWriter(s.getOutputStream());
pw.println(message);
pw.flush();
}
}
}
}
客户端——界面
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.IOException;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class ClientFrame extends JFrame {
private JPanel contentPane,panel;
private JTextField tfMessage;
private JButton btnSend;
private JTextArea textArea;
private String userName,ip;
private int i;
private ChatRoomClient client;
public ClientFrame() {
textArea=new JTextArea(10,10);
textArea.setEditable(false);
tfMessage =new JTextField(20);
btnSend = new JButton("发送");
userName = "燕双嘤";
ip = "127.0.0.1";
i = 8080;
try {
client = new ChatRoomClient(ip, i);
textArea.setText("连接成功\n");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}
setTitle("客户端");
tfMessage.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Date date = new Date();
SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
client.sendMessage(userName + ":" + sf.format(date) + ":\n" + tfMessage.getText());
tfMessage.setText("");
}
});
btnSend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Date date = new Date();
SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
client.sendMessage(userName + ":" + sf.format(date) + ":\n" + tfMessage.getText());
tfMessage.setText("");
}
});
this.userName = userName;
ReadMessageThread messageThread = new ReadMessageThread();
messageThread.start();
Container c=getContentPane();
contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
panel = new JPanel();
panel.setLayout(new FlowLayout());
contentPane.add(new JScrollPane(textArea),BorderLayout.CENTER);
panel.add(tfMessage);
panel.add(btnSend);
contentPane.add(panel,BorderLayout.SOUTH);
c.add(contentPane);
setBounds(100, 100, 450, 300);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class ReadMessageThread extends Thread {
public void run() {
while (true) {
String str = client.reciveMessage();
textArea.append(str + "\n");
}
}
}
}
客户端——方法类
import java.io.*;
import java.net.*;
public class ChatRoomClient {
private Socket socket;
private BufferedReader bufferReader;
private PrintWriter pWriter;
public ChatRoomClient(String host, int port) throws UnknownHostException, IOException {
socket = new Socket(host, port);
bufferReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pWriter = new PrintWriter(socket.getOutputStream());
}
public void sendMessage(String str) {
pWriter.println(str);
pWriter.flush();
}
public String reciveMessage() {
try {
return bufferReader.readLine();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void close() {
try {
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}