JAVA作业

来源:互联网 发布:淘宝女装店开店经验 编辑:程序博客网 时间:2024/05/18 02:32

使用TCP协议编写一个网络程序,设置服务器端的监听端口是8002,当与客户端建立连接后,服务器端向客户端发送数据“Hello, world”,客户端收到数据后打印输出。

##

import java.io.DataOutputStream;  import java.io.OutputStream;  import java.net.ServerSocket;  import java.net.Socket;  public class TCPServer {      public static void main(String[] args) throws Exception{          ServerSocket s=new ServerSocket(8002);          while (true) {              Socket s1=s.accept();              OutputStream os=s1.getOutputStream();              DataOutputStream dos=new DataOutputStream(os);              dos.writeUTF("Hello, world");              dos.close();              s1.close();          }      }  }  
import java.io.DataInputStream;  import java.io.InputStream;  import java.net.Socket;  /**  * 使用TCP协议编写一个网络程序,设置服务器端的监听端口是8002。  * 当与客户端建立连接后,服务器端向客户端发送数据“Hello, world”,客户端收到数据后打印输出。  *   * @author Vivinia  *  */  public class TCPClient {      public static void main(String[] args) throws Exception{          Socket s1=new Socket("127.0.0.1", 8002);          InputStream is=s1.getInputStream();          DataInputStream dis=new DataInputStream(is);          System.out.println(dis.readUTF());          dis.close();          s1.close();      }  }  

运行效果图:

这里写图片描述

使用UDP协议编写一个网络程序,设置接收端程序的监听端口是8001,发送端发送的数据是“Hello, world”。

##

import java.net.DatagramPacket;  import java.net.DatagramSocket;  import java.net.InetAddress;  /**  * 使用UDP协议编写一个网络程序,设置接收端程序的监听端口是8001,发送端发送的数据是“Hello, world”。  * @author Vivinia  */  //发送端  public class UDPSend {      public static void main(String[] args) throws Exception{          DatagramSocket ds=new DatagramSocket(3000);      //创建一个DatagramSocket对象          String str="Hello, world";           //要发送的数据          DatagramPacket dp=new DatagramPacket(str.getBytes(), str.length(),InetAddress.getByName("localhost"),8001);//创建一个要发送的数据包,包括数据,长度,接收端的ip及端口号          System.out.println("发送消息");          ds.send(dp);   //发送数据          ds.close();    //释放资源       }  }  
import java.net.DatagramPacket;  import java.net.DatagramSocket;  //接收端  public class UDPReceive {      public static void main(String[] args) throws Exception{          byte[] buf=new byte[1024];   //创建一个1024的字节数组,用于接收数据          DatagramSocket ds=new DatagramSocket(8001);  //定义一个DatagramSocket对象,监听的端口号为8954          DatagramPacket dp=new DatagramPacket(buf,1024);   //定义一个DatagramPacket对象,用于接收数据          System.out.println("等待接收数据");          ds.receive(dp);          //等待接收数据,没有则会阻塞          String str=new String(dp.getData());    //获取接收到的消息          System.out.println(str);          ds.close();      }  }  

运行效果图

这里写图片描述

原创粉丝点击