第十六周Java网络编程

来源:互联网 发布:哪个软件可以看陆小凤 编辑:程序博客网 时间:2024/05/29 19:50
//发送端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
原创粉丝点击