客户端
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;import javax.swing.JButton;import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;public class ClientSocketFrame extends JFrame {private PrintWriter writer; // 声明PrintWriter类对象private BufferedReader reader; // 声明BufferedReader对象private Socket socket; // 声明Socket对象private JTextArea ta_info; // 创建JtextArea对象private JTextField tf_send; // 创建JtextField对象private void connect() { // 连接套接字方法ta_info.append("尝试连接......\n"); // 文本域中信息信息try { // 捕捉异常socket = new Socket("127.0.0.1", 1978); // 实例化Socket对象while (true) {writer = new PrintWriter(socket.getOutputStream(), true);reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); // 实例化BufferedReader对象ta_info.append("完成连接。\n"); // 文本域中提示信息getServerInfo();}} catch (Exception e) {e.printStackTrace(); // 输出异常信息}}public static void main(String[] args) { // 主方法ClientSocketFrame clien = new ClientSocketFrame(); // 创建本例对象clien.setVisible(true); // 将窗体显示clien.connect(); // 调用连接方法}private void getServerInfo() {try {while (true) {if (reader != null) {String line = reader.readLine();// 读取服务器发送的信息if (line != null)ta_info.append("接收到服务器发送的信息:" + line + "\n"); // 显示服务器端发送的信息}}} catch (Exception e) {e.printStackTrace();} finally {try {if (reader != null) {reader.close();// 关闭流}if (socket != null) {socket.close(); // 关闭套接字}} catch (IOException e) {e.printStackTrace();}}}/*** Create the frame*/public ClientSocketFrame() {super();setTitle("客户端程序");setBounds(100, 100, 361, 257);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);final JPanel panel = new JPanel();getContentPane().add(panel, BorderLayout.NORTH);final JLabel label = new JLabel();label.setForeground(new Color(0, 0, 255));label.setFont(new Font("", Font.BOLD, 22));label.setText("一对一通信——客户端程序");panel.add(label);final JPanel panel_1 = new JPanel();getContentPane().add(panel_1, BorderLayout.SOUTH);final JLabel label_1 = new JLabel();label_1.setText("客户端发送的信息:");panel_1.add(label_1);tf_send = new JTextField();tf_send.setPreferredSize(new Dimension(140, 25));panel_1.add(tf_send);final JButton button = new JButton();button.addActionListener(new ActionListener() {public void actionPerformed(final ActionEvent e) {writer.println(tf_send.getText()); // 将文本框中信息写入流ta_info.append("客户端发送的信息是:" + tf_send.getText()+ "\n"); // 将文本框中信息显示在文本域中tf_send.setText(""); // 将文本框清空}});button.setText("发 送");panel_1.add(button);final JScrollPane scrollPane = new JScrollPane();getContentPane().add(scrollPane, BorderLayout.CENTER);ta_info = new JTextArea();scrollPane.setViewportView(ta_info);//}}
服务端
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;public class ServerSocketFrame extends JFrame {private JTextField tf_send;private JTextArea ta_info;private PrintWriter writer; // 声明PrintWriter类对象private BufferedReader reader; // 声明BufferedReader对象private ServerSocket server; // 声明ServerSocket对象private Socket socket; // 声明Socket对象socketpublic void getServer() {try {server = new ServerSocket(1978); // 实例化Socket对象ta_info.append("服务器套接字已经创建成功\n"); // 输出信息while (true) { // 如果套接字是连接状态ta_info.append("等待客户机的连接......\n"); // 输出信息socket = server.accept(); // 实例化Socket对象reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); // 实例化BufferedReader对象writer = new PrintWriter(socket.getOutputStream(), true);getClientInfo(); // 调用getClientInfo()方法}} catch (Exception e) {e.printStackTrace(); // 输出异常信息}}private void getClientInfo() {try {while (true) {String line = reader.readLine();// 读取客户端发送的信息if (line != null)ta_info.append("接收到客户机发送的信息:" + line + "\n"); // 显示客户端发送的信息}} catch (Exception e) {ta_info.append("客户端已退出。\n"); // 输出异常信息} finally {try {if (reader != null) {reader.close();// 关闭流}if (socket != null) {socket.close(); // 关闭套接字}} catch (IOException e) {e.printStackTrace();}}}public static void main(String[] args) { // 主方法ServerSocketFrame frame = new ServerSocketFrame(); // 创建本类对象frame.setVisible(true);frame.getServer(); // 调用方法}public ServerSocketFrame() {super();setTitle("服务器端程序");setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setBounds(100, 100, 379, 260);final JScrollPane scrollPane = new JScrollPane();getContentPane().add(scrollPane, BorderLayout.CENTER);ta_info = new JTextArea();scrollPane.setViewportView(ta_info);final JPanel panel = new JPanel();getContentPane().add(panel, BorderLayout.SOUTH);final JLabel label = new JLabel();label.setText("服务器发送的信息:");panel.add(label);tf_send = new JTextField();tf_send.setPreferredSize(new Dimension(150, 25));panel.add(tf_send);final JButton button = new JButton();button.addActionListener(new ActionListener() {public void actionPerformed(final ActionEvent e) {writer.println(tf_send.getText()); // 将文本框中信息写入流ta_info.append("服务器发送的信息是:" + tf_send.getText() + "\n"); // 将文本框中信息显示在文本域中tf_send.setText(""); // 将文本框清空}});button.setText("发 送");panel.add(button);final JPanel panel_1 = new JPanel();getContentPane().add(panel_1, BorderLayout.NORTH);final JLabel label_1 = new JLabel();label_1.setForeground(new Color(0, 0, 255));label_1.setFont(new Font("", Font.BOLD, 22));label_1.setText("一对一通信——服务器端程序");panel_1.add(label_1);}
}
结果展示
第二种
客户端
import java.io.*;
import java.net.Socket;
import java.util.Scanner;/*** Socket客户端**/
public class SocketClient {public static void main(String[] args) {Socket s = null;try {// 与ip为127.0.0.1、端口为12345的服务端建立连接s = new Socket("127.0.0.1", 12345);// 创建输入流接收服务端发送的消息(字节流)InputStream is = s.getInputStream();// 将服务端返回的字节流转化为字符流InputStreamReader isr = new InputStreamReader(is);// 创建字符流读取缓冲区,方便每行读取BufferedReader br = new BufferedReader(isr);// 创建输出流返回消息OutputStream os = s.getOutputStream();// 创建输出流缓冲PrintWriter pw = new PrintWriter(os);// 创建发送消息的线程Runnable rOut = () -> {boolean flag = true;while (flag) {try {// 接收控制台输入Scanner scan = new Scanner(System.in);String msg = scan.nextLine();// 将输入写入缓冲pw.println(msg);// 将缓冲内的数据推送至服务端并清空缓冲区pw.flush();} catch (Exception e) {flag = false;e.printStackTrace();}}};// 创建接收消息的线程Runnable rIn = () -> {boolean flag = true;while (flag) {try {// 逐行读取服务端返回的消息并打印String str = br.readLine();System.out.println("服务端的消息:" + str);} catch (IOException e) {flag = false;e.printStackTrace();}}};// 启动两个线程Thread tOut = new Thread(rOut);Thread tIn = new Thread(rIn);tOut.start();tIn.start();}catch (IOException e) {try {// 释放资源s.close();} catch (Exception exception) {exception.printStackTrace();}e.printStackTrace();}}
}
服务端
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;/*** Socket服务端**/
public class SocketServer {public static void main(String[] args) {ServerSocket ss = null;Socket s = null;try {// 创建监听端口为12345的Socket服务端ss = new ServerSocket(12345);System.out.println("服务端Socket服务已建立,等待客户端连接...");// 通过ss.accept()开始持续监听12345端口,当有连接时获取收到的包装成Socket的客户端对象s = ss.accept();// 获取客户端的IP地址和端口号String ip = s.getInetAddress().getHostAddress();int port = s.getPort();System.out.println("服务端与 " + ip + ":" + port + " 已建立连接");// 创建输入流接收客户端发送的消息(字节流)InputStream is = s.getInputStream();// 将客户端发送的字节流转化为字符流InputStreamReader isr = new InputStreamReader(is);// 创建字符流读取缓冲区,方便每行读取BufferedReader br = new BufferedReader(isr);// 创建输出流返回消息OutputStream os = s.getOutputStream();// 创建输出流缓冲PrintWriter pw = new PrintWriter(os);// 创建接受信息的线程Runnable rIn = () -> {boolean flag = true;while (flag) {try {// 逐行读取客户端发送的消息并打印String str = br.readLine();System.out.println("客户端的消息:" + str);} catch (IOException e) {flag = false;e.printStackTrace();}}};// 创建发送消息的线程Runnable rOut = () -> {boolean flag = true;while (flag) {try {// 接收控制台输入Scanner scan = new Scanner(System.in);String msg = scan.nextLine();// 将输入写入缓冲pw.println(msg);// 将缓冲内的数据推送至客户端并清空缓冲区pw.flush();} catch (Exception e) {flag = false;e.printStackTrace();}}};// 开启两个线程Thread tIn = new Thread(rIn);Thread tOut = new Thread(rOut);tIn.start();tOut.start();} catch (IOException e) {try {// 释放资源ss.close();s.close();} catch (Exception exception) {exception.printStackTrace();}e.printStackTrace();}}
}
结果