📄 testserver.java
字号:
package talk;
/**
* 本程序实现了聊天程序服务器端的用户界面及功能。
*/
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class TestServer extends JFrame implements ActionListener {
DataInputStream dis;
DataOutputStream dos;
JTextField tf;
JTextArea ta;
// 聊天程序服务器端主窗口用户初始界面。
public TestServer() {
this.setTitle("聊天程序服务端");
JScrollPane jp = new JScrollPane();
ta = new JTextArea(10, 10);
Panel p = new Panel();
tf = new JTextField(20);
JButton b = new JButton("发送");
b.addActionListener(this);
tf.addActionListener(this);
p.add(tf);
p.add(b);
jp.setViewportView(ta);
this.getContentPane().add(jp);
this.getContentPane().add("South", p);
this.setSize(350, 250);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
tf.requestFocus();
this.connect(); // 建立连接
this.createReadThread(); // 启动接受信息线程
}
// 建立双方通信的连接可,准备通信所需要的流。
public void connect() {
try {
ServerSocket ss = new ServerSocket(911); // 准备通信端口
Socket s2 = ss.accept();
InputStream is = s2.getInputStream();
dis = new DataInputStream(is); // 准备输入流
OutputStream os = s2.getOutputStream();
dos = new DataOutputStream(os); // 准备输出流
} catch (IOException e) {
System.out.println("连接服务器故障!");
}
}
// 启动接受对方信息线程的方法。
public void createReadThread() {
ReadThread rt = new ReadThread(this.ta, this.dis);
rt.start();
}
// 发送信息的时间处理方法。
public void actionPerformed(ActionEvent e) {
try {
String s = tf.getText();
dos.writeUTF(s); // 发送聊天信息
ta.append("自己说:" + s);
ta.append("\n");
tf.setText("");
tf.requestFocus();
} catch (IOException e1) {
e1.printStackTrace();
}
}
public static void main(String[] args) {
new TestServer();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -