📄 testclient.java
字号:
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestClient implements ActionListener{//继承了监听器接口
//
DataInputStream dis;
DataOutputStream dos;
JTextField tf;
JTextArea ta = new JTextArea(10,10);
String s11,s22;//分别负责接收客户端用户名,服务器IP
//---------------------------------
public TestClient(String s1,String s2){//构造方法 //客户端用户名 //服务器IP
JFrame f = new JFrame("我是:" + s1);
ta.setEditable(false);
JScrollPane jsp = new JScrollPane(ta);
f.getContentPane().add(jsp);
JPanel p = new JPanel();
tf = new JTextField(15);
JButton b = new JButton("Send");
b.setMnemonic(KeyEvent.VK_S);
b.setToolTipText("按此键发送信息");
b.addActionListener(this);
tf.addActionListener(this);
p.add(tf);
p.add(b);
f.getContentPane().add("South",p);
f.setSize(300,250);
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(1);
}
});
this.s11 = s1;//客户端用户名,在登录时输入的用户名
this.s22 = s2;//服务器IP
f.setVisible(true);
tf.requestFocus();
this.connect();//this是新创建的对象,调用本类的方法connect
this.createReadThread();
}
//--------------------------------------
public void connect(){
try{
Socket s2 = new Socket(s22,2006);//s22是服务器ip
InputStream is = s2.getInputStream();
dis = new DataInputStream(is); //DataInputStream dis;
OutputStream os = s2.getOutputStream();
dos = new DataOutputStream(os); //DataOutputStream dos;
}catch(IOException e){
System.out.println("连接服务器故障!");
System.exit(1);
}
}
//------------------------------------
public void createReadThread(){
ClientReadThread rt = new ClientReadThread(this.ta,this.dis);
rt.start();
}
//--------------------------------
public void actionPerformed(ActionEvent e)
{
try{
String s = tf.getText();
dos.writeUTF(s11 + "说: " + s); //以UTF-8编码 向输出流写出 自己说的内容
tf.setText("");
tf.requestFocus();
}
catch(Exception e1)
{
e1.printStackTrace();
System.exit(1);
}
}
}
class ClientReadThread extends Thread
{
JTextArea ta3;
DataInputStream dis;
public ClientReadThread(JTextArea t,DataInputStream d)//传入两个对象类型的参数
{
this.ta3 = t;
this.dis = d;
}
public void run()
{
try
{
while(true)
{
ta3.append("用户" + dis.readUTF());
ta3.append("\n");
ta3.setCaretPosition(ta3.getText().length());//文本区滚动到最下方
}
}
catch(IOException e)
{
System.out.println("连接中断!");
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -