一个基于socket连接的实现一个简单的聊天室。废话不多说,直接上代码:
客户端实现代码:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class TcpClient {
private Socket socket;
private BufferedReader bufferedReader;
private PrintWriter printWriter;
public TcpClient(String ip,String port) {
try {
this.socket = new Socket(ip,Integer.parseInt(port));//创建socket连接
System.out.println("client:" + socket);
bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
printWriter = new PrintWriter(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendMsg(String msg) {//发送消息
printWriter.println(msg);
printWriter.flush();
}
public String reciveMsg() {//接收消息
try {
return bufferedReader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
服务器端实现代码:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServer {
private ServerSocket serverSocket;
private Socket socket;
private BufferedReader bufferedReader;
private PrintWriter printWriter;
public TcpServer(String port) {
try {
this.serverSocket = new ServerSocket(Integer.parseInt(port));//创建服务器端套接字
System.out.println("server" + serverSocket);
socket = serverSocket.accept();//等待客户端连接
System.out.println("server:" + socket);
bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
printWriter = new PrintWriter(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendMsg(String msg) {//发送消息
printWriter.println(msg);
printWriter.flush();
}
public String reciveMsg() {//接收消息
try {
return bufferedReader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public boolean isClose() {//关闭socket
return socket.isClosed();
}
}
客户端界面及创建客户端对象:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JTextArea;
public class TCP_Server {
private JFrame frmChatapp;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTextField textField_4;
private JTextArea textArea;
private TcpServer tcpServer;
private TcpClient tcpClient;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TCP_Server window = new TCP_Server();
window.frmChatapp.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public TCP_Server() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmChatapp = new JFrame();//界面
frmChatapp.setTitle("ChatRoom");
frmChatapp.setBounds(100, 100, 936, 652);
frmChatapp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmChatapp.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("对方IP");//对方IP
lblNewLabel.setFont(new Font("宋体", Font.PLAIN, 18));
lblNewLabel.setBounds(40, 30, 122, 20);
frmChatapp.getContentPane().add(lblNewLabel);
textField = new JTextField();//对方IP
textField.setFont(new Font("宋体", Font.PLAIN, 18));
textField.setBounds(110, 29, 183, 23);
frmChatapp.getContentPane().add(textField);
textField.setColumns(10);
JLabel lblNewLabel_1 = new JLabel("用户名");//用户名
lblNewLabel_1.setFont(new Font("宋体", Font.PLAIN, 18));
lblNewLabel_1.setBounds(40, 82, 58, 20);
frmChatapp.getContentPane().add(lblNewLabel_1);
textField_1 = new JTextField();//用户名
textField_1.setFont(new Font("宋体", Font.PLAIN, 18));
textField_1.setBounds(110, 80, 183, 23);
frmChatapp.getContentPane().add(textField_1);
textField_1.setColumns(10);
JLabel label = new JLabel("端口号");//端口号
label.setFont(new Font("宋体", Font.PLAIN, 18));
label.setBounds(619, 34, 66, 20);
frmChatapp.getContentPane().add(label);
textField_2 = new JTextField();//端口号
textField_2.setFont(new Font("宋体", Font.PLAIN, 18));
textField_2.setBounds(695, 31, 183, 23);
frmChatapp.getContentPane().add(textField_2);
textField_2.setColumns(10);
JLabel label_1 = new JLabel("本机端口号");//本机端口号
label_1.setFont(new Font("宋体", Font.PLAIN, 18));
label_1.setBounds(585, 86, 92, 20);
frmChatapp.getContentPane().add(label_1);
textField_3 = new JTextField();//本机端口号
textField_3.setFont(new Font("宋体", Font.PLAIN, 18));
textField_3.setBounds(695, 83, 183, 23);
frmChatapp.getContentPane().add(textField_3);
textField_3.setColumns(10);
JButton button = new JButton("绑定端口号");//绑定端口号
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String ip = textField.getText();
String port = textField_2.getText();
tcpClient = new TcpClient(ip,port);//新建客户端
String localport = textField_3.getText();
tcpServer = new TcpServer(localport);
ReciveMsg reciveMsg = new ReciveMsg();
reciveMsg.start();
}
});
button.setFont(new Font("宋体", Font.PLAIN, 18));
button.setBounds(366, 82, 155, 23);
frmChatapp.getContentPane().add(button);
textArea = new JTextArea();
textArea.setFont(new Font("Monospaced", Font.PLAIN, 18));
textArea.setBounds(40, 131, 836, 380);
frmChatapp.getContentPane().add(textArea);
textField_4 = new JTextField();
textField_4.setFont(new Font("宋体", Font.PLAIN, 18));
textField_4.setBounds(40, 545, 692, 23);
frmChatapp.getContentPane().add(textField_4);
textField_4.setColumns(10);
JButton button_1 = new JButton("发送");//发送
button_1.setFont(new Font("宋体", Font.PLAIN, 18));
button_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String username = textField_1.getText();
System.out.println(username + ":" + textField_4.getText());
tcpClient.sendMsg(username + ":" + textField_4.getText());
System.out.println("发送数据成功!!!");
}
});
button_1.setBounds(779, 546, 97, 23);
frmChatapp.getContentPane().add(button_1);
}
private class ReciveMsg extends Thread {
@Override
public void run() {
while (true) {
String str = tcpServer.reciveMsg();//接收消息
if (str == null) {
break;
}
textArea.append(str + "\n");//把接收到的消息加入到文本域
System.out.println("接收数据成功!!!");
}
}
}
}
服务器端界面及创建代码:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JTextArea;
public class TCP_Server2 {
private JFrame frmChatapp;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTextField textField_4;
private JTextArea textArea;
private TcpServer tcpServer;
private TcpClient tcpClient;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TCP_Server2 window = new TCP_Server2();
window.frmChatapp.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public TCP_Server2() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmChatapp = new JFrame();
frmChatapp.setTitle("ChatRoom");
frmChatapp.setBounds(100, 100, 936, 652);
frmChatapp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmChatapp.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("对方IP");//对方IP
lblNewLabel.setFont(new Font("宋体", Font.PLAIN, 18));
lblNewLabel.setBounds(40, 30, 122, 20);
frmChatapp.getContentPane().add(lblNewLabel);
textField = new JTextField();//对方IP
textField.setFont(new Font("宋体", Font.PLAIN, 18));
textField.setBounds(110, 29, 183, 23);
frmChatapp.getContentPane().add(textField);
textField.setColumns(10);
JLabel lblNewLabel_1 = new JLabel("用户名");//用户名
lblNewLabel_1.setFont(new Font("宋体", Font.PLAIN, 18));
lblNewLabel_1.setBounds(40, 82, 58, 20);
frmChatapp.getContentPane().add(lblNewLabel_1);
textField_1 = new JTextField();//用户名
textField_1.setFont(new Font("宋体", Font.PLAIN, 18));
textField_1.setBounds(110, 80, 183, 23);
frmChatapp.getContentPane().add(textField_1);
textField_1.setColumns(10);
JLabel label = new JLabel("端口号");//端口号
label.setFont(new Font("宋体", Font.PLAIN, 18));
label.setBounds(619, 34, 66, 20);
frmChatapp.getContentPane().add(label);
textField_2 = new JTextField();//端口号
textField_2.setFont(new Font("宋体", Font.PLAIN, 18));
textField_2.setBounds(695, 31, 183, 23);
frmChatapp.getContentPane().add(textField_2);
textField_2.setColumns(10);
JLabel label_1 = new JLabel("本机端口号");//本机端口号
label_1.setFont(new Font("宋体", Font.PLAIN, 18));
label_1.setBounds(585, 86, 92, 20);
frmChatapp.getContentPane().add(label_1);
textField_3 = new JTextField();//本机端口号
textField_3.setFont(new Font("宋体", Font.PLAIN, 18));
textField_3.setBounds(695, 83, 183, 23);
frmChatapp.getContentPane().add(textField_3);
textField_3.setColumns(10);
JButton button = new JButton("绑定端口号");//绑定端口号
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String ip = textField.getText();
String localport = textField_3.getText();
tcpServer = new TcpServer(localport);
String port = textField_2.getText();
tcpClient = new TcpClient(ip,port);
ReciveMsg reciveMsg = new ReciveMsg();
reciveMsg.start();
}
});
button.setFont(new Font("宋体", Font.PLAIN, 18));
button.setBounds(366, 82, 155, 23);
frmChatapp.getContentPane().add(button);
textArea = new JTextArea();
textArea.setFont(new Font("Monospaced", Font.PLAIN, 18));
textArea.setBounds(40, 131, 836, 380);
frmChatapp.getContentPane().add(textArea);
textField_4 = new JTextField();
textField_4.setFont(new Font("宋体", Font.PLAIN, 18));
textField_4.setBounds(40, 545, 692, 23);
frmChatapp.getContentPane().add(textField_4);
textField_4.setColumns(10);
JButton button_1 = new JButton("发送");//发送
button_1.setFont(new Font("宋体", Font.PLAIN, 18));
button_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String username = textField_1.getText();
System.out.println(username + ":" + textField_4.getText());
tcpClient.sendMsg(username + ":" + textField_4.getText());
System.out.println("发送数据成功!!!");
}
});
button_1.setBounds(779, 546, 97, 23);
frmChatapp.getContentPane().add(button_1);
}
private class ReciveMsg extends Thread {
@Override
public void run() {
while (true) {
String str = tcpServer.reciveMsg();
if (str == null) {
break;
}
textArea.append(str + "\n");
System.out.println("接收数据成功!!!");
}
}
}
}
运行截图:
左边为服务器端,右边为客户端,运行时,输入完毕信息后,先点击左边的绑定端口号,再点击右边的绑定端口号。
(博主为一名学生,比较懒惰,如果有有什么需要的学校作业,可以在下方留言,如果有我会发出来的)。