import java.net.*;
public class TheSender {
public static void main(String[] args) throws Exception{
DatagramSocket ds=new DatagramSocket(3000);
String str="Hello,world";
DatagramPacket dp=new DatagramPacket(str.getBytes(),str.length(),
InetAddress.getByName("localhost"),8001);
System.out.println("发送信息");
ds.send(dp);
ds.close();
}
}
import java.net.*;
public class TheSender {
public static void main(String[] args) throws Exception{
DatagramSocket ds=new DatagramSocket(3000);
String str="Hello,world";
DatagramPacket dp=new DatagramPacket(str.getBytes(),str.length(),
InetAddress.getByName("localhost"),8001);
System.out.println("发送信息");
ds.send(dp);
ds.close();
}
}
运行结果:
等待接收数据...
Hello,world from 127.0.0.1 : 3000
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) throws Exception{
new TCPServer().listen();
}
}
class TCPServer{
private static final int PORT=8002;
public void listen() throws Exception{
ServerSocket ss=new ServerSocket(PORT);
Socket client=ss.accept();
OutputStream os=client.getOutputStream();
System.out.println("开始与客户端交互数据。");
os.write(("Hello, world").getBytes());
Thread.sleep(2500);
System.out.println("结束与客户端交互数据。");
os.close();
client.close();
}
}
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) throws Exception{
new TCPServer().listen();
}
}
class TCPServer{
private static final int PORT=8002;
public void listen() throws Exception{
ServerSocket ss=new ServerSocket(PORT);
Socket client=ss.accept();
OutputStream os=client.getOutputStream();
System.out.println("开始与客户端交互数据。");
os.write(("Hello, world").getBytes());
Thread.sleep(2500);
System.out.println("结束与客户端交互数据。");
os.close();
client.close();
}
}
运行结果:
开始与客户端交互数据。
结束与客户端交互数据。
Hello, world