客户端
java
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);
//
}
}
服务端
java
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对象socket
public 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);
}
}
结果展示
第二种
客户端
java
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();
}
}
}
服务端
java
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();
}
}
}
结果