📄 client.java
字号:
/*
* Created on 2005-11-3
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package xdevelop.nioserver.chat;
/**
* @author chengang
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class Client extends Frame implements ActionListener, Runnable {
private TextField tf1, tf2;
private Label la1, la2;
private TextArea ta1, ta2;
private Socket s;
private Button b, l;
private BufferedReader br = null;
private PrintWriter pw = null;
// static String port,ip;
public static void main(String arg[]) {
new Client();
//if(arg[0].length()!=0) ip=arg[0];
//if(arg[1].length()!=0) port=arg[1];
}
//完成构造函数的说明
public Client() {
//完成ip地址与端口的建立
setLayout(new GridLayout(6, 1));
Panel panel = new Panel();
tf1 = new TextField(20);
tf2 = new TextField(10);
la1 = new Label("IP地址 ");
la2 = new Label("对应端口 ");
Button l = new Button("连接");
l.setBackground(Color.green);
//l.addActionListener(this);
panel.add(la1);
panel.add(tf1);
panel.add(la2);
panel.add(tf2);
panel.add(l);
add(panel);
//输入框与显示框
ta1 = new TextArea(100, 300);
add(new Label("消息框"));
add(ta1);
add(new Label("用户输入框"));
ta2 = new TextArea(30, 300);
add(ta2);
Panel p2 = new Panel();
b = new Button("发送");
b.setBackground(Color.yellow);
p2.add(b);
add(p2);
setTitle("客户端");
setSize(300, 450);
setResizable(false);
setVisible(true);
//捕获各种的异常
l.addActionListener(this);
// b.addActionListener(this);
//增加了一个关闭的事件
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent exit) {
System.exit(0);
}
});
Thread ThreadReader = new Thread(this);
ThreadReader.start();
b.addActionListener(this);
}
public void run() {
while (true) {
try {
ta1.append("\n #_____________________________#\n"
+ br.readLine());
} catch (Exception exo) {
}
}
}
//客户向服务端发送消息啊!
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if ("发送".equals(command)) {
if (ta2.getText().trim() != null) {
ta1.append("\n 客户端的消息:\n" + ta2.getText());
pw.println(ta2.getText() + "\n");//" \n 客户短信: \n "
} else if (ta2.getText().trim() == null) {
ta1.append("请输入完整的IP地址与端口以及、\n" + "不能空发消息");
}
ta2.setText(" "); //结束的时候清空文本框
} else if ("连接".equals(command)) {
try {
//借助连接的按钮完成远程pc的连接的工作。建立输入与输出流两个工具
s = new Socket(tf1.getText().toString(), Integer.parseInt((tf2
.getText()).trim()));
//Integer.parseInt((tf2.getText()).trim())
br = new BufferedReader(new InputStreamReader(s
.getInputStream()));
pw = new PrintWriter(s.getOutputStream(), true);
//ta1.append("\n 服务端来消息:\n"+br.readLine());
} catch (Exception ex) {
//ta1.append("产生了输入输出异常无法完成交互!");
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -