📄 client.java
字号:
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Client
{ public static void main(String args[])
{ new A("小狗聊天室");
}
}
class A extends JFrame implements ActionListener ,Runnable
{
JTextArea main,part;
JLabel zhu,fu;
JButton link,sent;
JScrollPane aa,bb;
JTextField show1,show2;
Socket socket1=null;
DataInputStream in=null;
DataOutputStream out=null;
Thread thread1;
A(String s)
{super(s);
setBounds(200,30,620,620);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
socket1=new Socket();
main=new JTextArea("");
main.setEditable(false);
main.setLineWrap(true);
aa=new JScrollPane(main);
part=new JTextArea("");
part.setLineWrap(true);
bb=new JScrollPane(part);
zhu=new JLabel(new ImageIcon("cat.jpg"));
fu=new JLabel(new ImageIcon("dog.jpg"));
link=new JButton("连接服务器");
link.addActionListener(this);
sent=new JButton("发送信息");
sent.setEnabled(false);
sent.addActionListener(this);
//send.setEnabled(false);
show1=new JTextField("远程小猫");
show2=new JTextField("本地小狗");
thread1=new Thread(this);
show1.setEditable(false);
show2.setEditable(false);
Font f=new Font("华文中宋",Font.BOLD,17);
main.setFont(f); part.setFont(f); show1.setFont(f);
show2.setFont(f);link.setFont(f);sent.setFont(f);
Container con=getContentPane();
con.setLayout(null);
aa.setBounds(0,0,450,350);
bb.setBounds(0,360,450,150);
link.setBounds(10,535,150,40);
sent.setBounds(260,535,120,40);
zhu.setBounds(470,50,135,135);
show1.setBounds(470,235,135,30);
fu.setBounds(470,360,135,135);
show2.setBounds(470,530,135,30);
con.add(aa);con.add(bb);con.add(link);
con.add(sent);con.add(zhu);con.add(show1);
con.add(fu);
con.add(show2);
con.validate();
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==link)
{ try
{ if(socket1.isConnected())
{}
else
{ InetAddress address=InetAddress.getByName("127.0.0.1");
InetSocketAddress socketAddress=new InetSocketAddress(address,4331);
socket1.connect(socketAddress);
in =new DataInputStream(socket1.getInputStream());
out = new DataOutputStream(socket1.getOutputStream());
sent.setEnabled(true);
main.append("已连接\n");
thread1.start();
}
}
catch (IOException ee){}
}
if(e.getSource()==sent)
{ String s=part.getText();
if(s!=null)
{ try {
out.writeUTF(s);
main.append("本地小狗:"+s+"\n");
part.setText("");
}
catch(IOException e1){}
}
}
}
public void run()
{ String s=null;
while(true)
{ try{ s=in.readUTF();
main.append("远程小猫:"+s+"\n");
}
catch(IOException e)
{ main.append("与服务器断开");
break;
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -