📄 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 + -