📄 client.java
字号:
//client
import java.io.*;
import java.net.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
//There are three areas in a client frame.The left area of the frame is to display the messages from
//all clients.
//The bottom area of this frame is used to enter the message, when the user presses the enter key,
//the current message together with the user name is sent to the server.
//The right area of this frame is to show current user.
public class Client implements Runnable {
public static void main(String[] args) {
//creat many users in chatting room
Client client1=new Client("clent1");
Client client2=new Client("clent2");
Client client3=new Client("clent3");
Thread thread1=new Thread(client1);
Thread thread2=new Thread(client2);
Thread thread3=new Thread(client3);
thread1.start();
thread2.start();
thread3.start();
}
public String name;
JTextField jtf;
JTextArea jta;
JTextArea jta2;
Socket s;
DataOutputStream out;
DataInputStream in;
public Client(String m){
name=m;
JFrame frame=new JFrame(this.name);
frame.setSize(300,300);
jta=new JTextArea();
jta2=new JTextArea();
jta.setEditable(false);
jtf=new JTextField();
jtf.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
send();
}
});
frame.getContentPane().add(new JScrollPane(jta));
frame.getContentPane().add(jta2,"East");
jta2.setSize(100, 300);
jta2.append("user name"+"\n"+":"+name);
frame.getContentPane().add(jtf,"South");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
Socket s=null;
try {
s=new Socket("127.0.0.1",7200);
//TCP communication
in=new DataInputStream(s.getInputStream());
out=new DataOutputStream(s.getOutputStream());
}
catch (UnknownHostException e) {
System.out.println("Sock:"+e.getMessage());
}
catch (EOFException e) {
System.out.println("EOF:"+e.getMessage());
}
catch (IOException e) {
System.out.println("IO:"+e.getMessage());
}
}
public void run(){
receive();
}
public void receive(){
while(true){
try {
String text=in.readUTF();
this.jta.append(text+"\n");
}
catch (IOException e) {
e.printStackTrace();
return;
}
}
}
public void send(){
try{
String text=this.jtf.getText();
this.jtf.setText("");
out.writeUTF(this.name);
out.writeUTF(text);
out.flush();
}
catch(IOException e){
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -