📄 client.java
字号:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Client extends JPanel implements Runnable {
private JTextField tf = new JTextField();
private JTextArea ta = new JTextArea();
private JScrollPane js = new JScrollPane(ta);
// 连接服务器
private Socket socket;
// 获得输入流输出流
private DataOutputStream dout;
private DataInputStream din;
// 构造
public Client(String host, int port) {
// 布局
setLayout(new BorderLayout());
add("North", tf);
add("Center", js);
// 注册事件监听 并且 发送信息到服务器
tf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
processMessage(e.getActionCommand());//获得文本区内容
}
});
//连接服务器
try{
socket = new Socket(host,port);
System.out.println("connected to "+socket);
//获得输入输出流
din = new DataInputStream(socket.getInputStream());
dout = new DataOutputStream(socket.getOutputStream());
//调用构造时,运行线程
new Thread(this).start();//防止阻塞
}
catch(IOException ie)
{
System.out.println(ie);
}
}
private void processMessage(String message)
{
try
{
dout.writeUTF(message);
//清空文本框
tf.setText("");
}
catch(IOException ie)
{
System.out.println(ie);
}
}
//线程---用于 读取 服务器 聊天信息
public void run()
{
try
{
while(true)
{
String message= din.readUTF();
//将读取的聊天信息,添加 到 ta中
ta.append(message+"\n");
}
}
catch(IOException ie)
{
System.out.println(ie);
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -