📄 client_socket.java
字号:
import java.io.*;
import java.net.*;
import java.util.*;
import java.text.*;
import java.awt.*;
import java.awt.event.*;
public class Client_Socket implements ActionListener{
Frame f;
TextField tf;
Button b1,b2;
Label l1;
static TextArea ta1,ta2;
String IpAddr;
Socket socket;
static BufferedReader in;
PrintWriter out;
BufferedReader wt;
String message;
public void display(){
f=new Frame("聊天室");
f.setSize(500,450);
f.setLocation(500,100);
f.setBackground(Color.pink);
f.setLayout(new FlowLayout(FlowLayout.LEFT));
tf=new TextField("在此输入服务器的IP地址",25);
tf.setEditable(true);
f.add(tf);
b1=new Button("连接");
b2=new Button("发送");
f.add(b1);
l1=new Label("消息");
ta1=new TextArea();
ta1.setEditable(false);
ta2=new TextArea();
f.add(ta1);
f.add(l1);
f.add(ta2);
f.add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
f.addWindowListener(new WinClose());
f.setVisible(true);
}
public void actionPerformed(ActionEvent e){
if((e.getSource())==b1){
IpAddr=tf.getText();
try{
getConnection(IpAddr);
}
catch(IOException e1){
}
}
if((e.getSource())==b2){
try{
sendMessage();
}
catch(IOException e2){
}
}
}
public void sendMessage()throws IOException{
SimpleDateFormat sdf=new SimpleDateFormat();
sdf.applyPattern("HH:mm:ss");
String timeStr = sdf.format(new Date());
message=ta2.getText();
ta2.setText("");
ta1.append("Client:"+message+" ["+timeStr+"]\n");
out.println("Client:"+message+" ["+timeStr+"]");
if(message.equals("END"))
System.exit(0);
getMessage();
}
public void getMessage()throws IOException{
String str;
try{
str=in.readLine();
ta1.append(str+"\n");
if(str.equals("END"))
System.exit(0);
}
catch(IOException e){
}
}
public void getConnection(String Ipaddr)throws IOException{
String str;
InetAddress addr=InetAddress.getByName(IpAddr);
System.out.println("addr="+addr);
socket=new Socket(addr,8888);
System.out.println("socket="+socket);
in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
}
public static void main(String[] args)throws IOException{
Client_Socket cs=new Client_Socket();
cs.display();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -