v0.1
编写客户端,继承Frame
设置窗体基本信息(位置大小,添加文本域和文本框)
setBounds(300, 300, 400, 350);//设置位置大小
add(tf,BorderLayout.SOUTH);
add(ta,BorderLayout.NORTH);
pack();//自动调整
setVisible(true);
给窗体添加关闭功能(使用匿名内部类)
addWindowListener(new WindowAdapter() {//注册监听器
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
v0.2
给文本框注册监听
将文本框输入内容显示在文本域中
tf.addActionListener(new ActionListener() {//文本框注册监听
public void actionPerformed(ActionEvent e) {
String s=tf.getText().trim();
ta.setText(s);
tf.setText("");//清空输入框
}
});
v0.3
创建服务器,等待连接
ServerSocket ss=new ServerSocket(8888);
while (true) {
Socket s=ss.accept();
System.out.println("A client connected!");
}
客户端连接服务器
//连接服务器
public void connect() {
try {
s=new Socket("127.0.0.1", 8888);
System.out.println("connected!");
} catch (IOException e) {
e.printStackTrace();
}
}
v0.4
客户端获取输出流,输出信息
当前版本,只能发送一条信息
//发送信息
public void send(String str) {
try {
PrintWriter pw=new PrintWriter(s.getOutputStream());
pw.println(str);
pw.flush();
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
服务器获取打印流,显示信息
BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
String str=br.readLine();
System.out.println(str);
v0.5
解决只能发送一条信息的问题
用户关闭窗体时,断开连接关闭资源
//断开连接
public void disconnect() {
try {
pw.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
解决只能接收一条信息的问题
while (bflag) {
String str = br.readLine();
if (str != null && str.length() > 0) {
System.out.println(str);
}
}
br.close();
s.close();
v0.6
实现多客户端给服务器发送消息
使用多线程
//线程类
class Client implements Runnable{
Socket s=null;
BufferedReader br=null;
public Client(Socket s){
this.s=s;
try {
br=new BufferedReader(new InputStreamReader(s.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (true) {
try {
String s = br.readLine();
if(s!=null)System.out.println(s);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}