📄 client.java
字号:
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Client extends JFrame {
private JTextField jtf = new JTextField();
private JTextArea jta = new JTextArea();
private ObjectOutputStream outstream;
private ObjectInputStream instream;
private String message = "";
private String serverinfo;
private Socket client;
public Client(String host) {
super("客户端");
serverinfo = host;
Container container = getContentPane();
jtf.setEnabled(false);
jtf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
sendData(event.getActionCommand());
}
});
container.add(jtf, BorderLayout.NORTH);
container.add(new JScrollPane(jta), BorderLayout.CENTER);
setSize(300, 150);
setVisible(true);
}
public void runClient() { //客户端主程序
try {
connectToServer();
getStreams();
processConnection();
closeConnection();
}
catch (EOFException eofException) {
System.out.println("服务端已中止连接");
}
catch (IOException ioException) {
ioException.printStackTrace();
}
}
private void getStreams() throws IOException { //获取数据流
outstream = new ObjectOutputStream(client.getOutputStream());//输出流
outstream.flush();
instream = new ObjectInputStream(client.getInputStream()); //获取输入流
jta.append("\n获取I/O流\n");
}
private void connectToServer() throws IOException { //连接至服务器
jta.setText("正在连接...\n");
client = new Socket(InetAddress.getByName(serverinfo), 5000);
jta.append("连接至: " + client.getInetAddress().getHostName());
}
private void processConnection() throws IOException { //连接过程处理
// 将文本框jtf使能,客户端可通过其发送信息
jtf.setEnabled(true);
do {
try {
message = (String) instream.readObject();
jta.append("\n" + message);
jta.setCaretPosition(jta.getText().length());
}
catch (ClassNotFoundException classNotFoundException) {
jta.append("\n接收到未知数据");
}
}
while (!message.equals("服务端:中止连接"));
}
private void closeConnection() throws IOException { //关闭连接
jta.append("\n正在关闭连接");
outstream.close();
instream.close();
client.close();
}
private void sendData(String message) { //向服务端发送数据
try {
outstream.writeObject("客户端:" + message);
outstream.flush();
jta.append("\n客户端:" + message);
}
catch (IOException ioException) {
jta.append("\n输入非法内容");
}
}
public static void main(String args[]) {
Client client;
if (args.length == 0)
client = new Client("127.0.0.1");
else
client = new Client(args[0]);
client.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
client.runClient();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -