?? client.java
字號:
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
public class Client
{
Frame f=new Frame("客戶");
Label lbta=new Label("顯示");
TextArea ta=new TextArea(15,15);//消息接收顯示框
Label lbip=new Label("IP");
TextField ip=new TextField("localhost",10);//IP輸入框
Label lbport=new Label("端口");
TextField port=new TextField("4444",2);//輸入端口
Label lbname=new Label("用戶名");
TextField name=new TextField("王紅",5);//輸入用戶名
Label lbmima=new Label("密碼");
TextField mima=new TextField("073411",5);//輸入密碼
Button b1=new Button("登錄");
TextField xiaoxi=new TextField("",15);//編輯消息的那個框框
Button b2=new Button("發送");//發送消息按鈕
Socket client=null;
public Client()
{
ta.setBackground(Color.WHITE);
ta.setForeground(Color.BLACK);
ta.setEditable(false);
f.add(ta,BorderLayout.SOUTH);
Panel p1=new Panel();
Panel p2=new Panel();
p1.add(lbip);
p1.add(ip);
p1.add(lbport);
p1.add(port);
p2.add(lbname);
p2.add(name);
p2.add(lbmima);
p2.add(mima);
p2.add(b1);
p2.add(xiaoxi);
p2.add(b2);
f.add(p1,BorderLayout.NORTH);
f.add(p2,BorderLayout.EAST);
f.setResizable(false);//不能調節窗口大小
f.addWindowListener(new MyActionListener());
b1.addActionListener(new MyActionListener());//給登錄按鈕添加事件處理器
b2.addActionListener(new MyActionListener());//給發送按鈕添加事件處理器
f.pack();
f.setVisible(true);
//窗體關閉
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public static void main(String args[])
{
Client c=new Client();
}
//事件處理類
class MyActionListener extends WindowAdapter implements ActionListener{
public void actionPerformed(ActionEvent e){
// if(name.getText().equals("123") & mima.getText().equals("123")){
if(e.getActionCommand().equals("登錄")){
String tmp=null;
try {
//創建到指定服務器的socket連接
client = new Socket(ip.getText(),Integer.parseInt(port.getText()));
tmp="連接成功\n";
ReadMsg rs=new ReadMsg();
rs.start();
} catch (Exception ex) {
tmp="連接失敗\n";
}
ta.setText(tmp);//顯示登錄成功或失敗信息
}
if(e.getActionCommand().equals("發送")){
OutputStream os =null;
PrintStream ps =null;
try {
os = client.getOutputStream();
ps = new PrintStream(os);
ps.println(xiaoxi.getText());
} catch (Exception ex1) {
//ex1.printStackTrace();
ta.append("發送失敗\n");
}
}
}
public void windowClosing(WindowEvent e){
System.exit(0);//關閉窗口,退出程序
}
}
//內部類,負責接收從服務器上轉發回的消息
class ReadMsg extends Thread{
public void run(){
InputStream is =null;
BufferedReader br=null;
String msg = null;
OutputStream os = null;
PrintStream ps = null;
try {
is = client.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
//客戶端連接成功后,首先發送昵稱過去
os = client.getOutputStream();
ps = new PrintStream(os);
ps.println(name.getText());
} catch (Exception ex1) {
//ex1.printStackTrace();
}
while(true){
try {
while ((msg = br.readLine()) != null) {
ta.append(msg + "\n");
}
} catch (Exception ex) {
//ex.printStackTrace();
}
}
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -