📄 example1103_tcpclient.java
字号:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;
public class Example1103_TCPClient extends JFrame implements ActionListener
{
JTextField hostfield;
JTextField portfield;
JTextField messfield;
JButton sendbutt;
JTextArea result;
JLabel status;
public Example1103_TCPClient()
{
super("TCP-Client");
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container con=getContentPane();
hostfield=new JTextField();
portfield=new JTextField();
messfield=new JTextField();
sendbutt=new JButton("发送");
result=new JTextArea();
status=new JLabel("ok");
result.setEditable(false);
sendbutt.addActionListener(this);
Box box=Box.createHorizontalBox();
box.add(new JLabel("目的地"));
box.add(hostfield);
box.add(new JLabel("端口"));
box.add(portfield);
box.add(new JLabel("消息内容"));
box.add(messfield);
box.add(sendbutt);
con.add(box,"North");
con.add(new JScrollPane(result),"Center");
con.add(status,"South");
setBounds(0,getToolkit().getScreenSize().height/2-20,getToolkit().getScreenSize().width,getToolkit().getScreenSize().height/2-20);
setVisible(true);
}
public void actionPerformed(ActionEvent evt)
{
status.setText("ok");
if (evt.getSource()==sendbutt)
{
try
{
String host=hostfield.getText();
int port=Integer.parseInt(portfield.getText());
Socket socket=new Socket(host,port);
DataInputStream in=new DataInputStream(socket.getInputStream());
DataOutputStream out=new DataOutputStream(socket.getOutputStream());
String outmes=messfield.getText();
out.writeUTF(outmes);
String inmes=in.readUTF();
result.append("Send: "+outmes+" ; Receive: "+inmes+" from "+socket.getInetAddress()+"\n");
in.close();
out.close();
socket.close();
}
catch (UnknownHostException e)
{
status.setText("UnknownHostException");
}
catch (IOException e)
{
status.setText("IOException");
}
catch (NumberFormatException e)
{
status.setText("NumberFormatException");
}
}
}
public static void main(String[] args)
{
new Example1103_TCPClient();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -