📄 socketexample.java
字号:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.net.*;
import java.io.*;
public class SocketExample extends Applet
{
private Socket sock;
private DataInputStream dataIn;
private DataOutputStream dataOut;
String srvName;
int srvPort;
Label label1,label2;
TextField textfield_send,textfield_receive;
Button button_send;
public void init()
{
setLayout(new GridLayout(2,3));
label1 = new Label("请输入要发送的字符串:");
label2 = new Label("Server 返回的字符串:");
textfield_send = new TextField();
textfield_receive = new TextField();
textfield_receive.setEditable(false);
srvName = "127.0.0.1";
srvPort = 7;
makeConnection();
button_send = new Button("发送");
button_send.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
send_recive();
}
});
add(label1);
add(textfield_send);
add(button_send);
add(label2);
add(textfield_receive);
}
private void send_recive()
{
try
{
dataOut.writeUTF(textfield_send.getText());
dataOut.flush();
System.out.println(textfield_send.getText());
textfield_receive.setText(dataIn.readUTF());
}
catch (IOException IOE)
{
System.err.println(IOE);
}
}
private void makeConnection()
{
try
{
InetAddress srvAddr=InetAddress.getByName(srvName);
sock=new Socket(srvAddr,srvPort);
dataIn=new DataInputStream(new BufferedInputStream(sock.getInputStream()));
dataOut=new DataOutputStream(new BufferedOutputStream(sock.getOutputStream()));
System.err.println("Connection to server ok");
}
catch (IOException io)
{
System.err.println("Error:"+io);
}
}
public void stop()
{
try
{
dataOut.close();
dataIn.close();
sock.close();
}
catch (IOException io) {};
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -