?? testclient.java
字號:
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestClient implements ActionListener{//繼承了監(jiān)聽器接口
//
DataInputStream dis;
DataOutputStream dos;
JTextField tf;
JTextArea ta = new JTextArea(10,10);
String s11,s22;//分別負(fù)責(zé)接收客戶端用戶名,服務(wù)器IP
//---------------------------------
public TestClient(String s1,String s2){//構(gòu)造方法 //客戶端用戶名 //服務(wù)器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("按此鍵發(fā)送信息");
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;//服務(wù)器IP
f.setVisible(true);
tf.requestFocus();
this.connect();//this是新創(chuàng)建的對象,調(diào)用本類的方法connect
this.createReadThread();
}
//--------------------------------------
public void connect(){
try{
Socket s2 = new Socket(s22,2006);//s22是服務(wù)器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("連接服務(wù)器故障!");
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編碼 向輸出流寫出 自己說的內(nèi)容
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)//傳入兩個對象類型的參數(shù)
{
this.ta3 = t;
this.dis = d;
}
public void run()
{
try
{
while(true)
{
ta3.append("用戶" + dis.readUTF());
ta3.append("\n");
ta3.setCaretPosition(ta3.getText().length());//文本區(qū)滾動到最下方
}
}
catch(IOException e)
{
System.out.println("連接中斷!");
}
}
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -