java语言基础(100)——网络编程(udp tcp发收数据)

来源:互联网 发布:淘宝五折换购 编辑:程序博客网 时间:2024/06/04 18:49

我们知道,在计算机网络中,每个主机都有一个唯一标识,我们称之为IP地址,有了某个主机的ip地址才可以与之通信,所以说到网络编程,我们就必须用到InetAddress类,该类提供将主机名解析为其 IP 地址(或反之)的方法,可以让我们确定一台主机。其用法简单我们就不单独讲了,请参考http://tool.oschina.net/uploads/apidocs/jdk-zh/java/net/InetAddress.html


UDP协议发送和接收数据(DatagramSocket)

UDP发送数据demo:

package netDemo;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;public class udpSendDemo {/** * UDP发送数据编程步骤 * 1 创建对象 * 2 封装数据 * 3 发送数据 * 4 回收资源 *  * udp协议发送接收数据被封装在  DatagramSocket 类中 * @throws IOException  */public static void main(String[] args) throws IOException {          // 创建对象 DatagramSocket ds = new DatagramSocket();  // 键盘录入 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = null;  while((line=br.readLine())!=null){ if("exit".equals(line)){ break; } // 封装数据包  //DatagramPacket(byte[] buf, int length, InetAddress address, int port) byte[] by = line.getBytes(); DatagramPacket dp = new DatagramPacket( by,by.length, InetAddress.getByName("192.168.1.255"),8888);  // 发送数据 send(DatagramPacket p)  ds.send(dp); }    // 回收资源 ds.close();}}


UDP接收数据demo:

package netDemo;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress; public class udpReceiveDemo {/** * UDP接收数据编程步骤 * 1 创建接收端socket对象 * 2 创建数据包作为接收容器 * 3 接收数据 * 4 处理数据显示数据 * 5 释放资源  * @throws Exception  */public static void main(String[] args) throws Exception {// 创建接收对象DatagramSocket ds = new DatagramSocket(8888); // 创建数据包byte[] by = new byte[1024];int len = by.length;DatagramPacket dp = new DatagramPacket(by,len);while(true){// 接收数据包ds.receive(dp);// 处理数据包并显示byte[] by2 = dp.getData();int length = dp.getLength();String s = new String(by2,0,length);String ip = dp.getAddress().getHostAddress();System.out.println(ip +":"+s);}// 释放资源 服务器端应该总是开启状态 所以用不到资源回收    //ds.close();}}

多线程实现同一个窗口(聊天室)既发送又接收数据:

发送线程:

package netDemo;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;import java.net.UnknownHostException;public class SendThread implements Runnable {    private DatagramSocket ds;public SendThread(DatagramSocket ds) { this.ds = ds;}@Overridepublic void run() { // 键盘录入 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = null;  try {while((line=br.readLine())!=null){ if("exit".equals(line)){ break; } // 封装数据包  //DatagramPacket(byte[] buf, int length, InetAddress address, int port) byte[] by = line.getBytes(); DatagramPacket dp = new DatagramPacket( by,by.length, InetAddress.getByName("192.168.1.255"),8888);  // 发送数据 send(DatagramPacket p)  ds.send(dp); }} catch (UnknownHostException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{// 回收资源 ds.close();}   }}


接收线程:

package netDemo;import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;public class ReceiveThread implements Runnable { private DatagramSocket ds;    public ReceiveThread(DatagramSocket ds){    this.ds = ds;    }@Overridepublic void run() {// 创建数据包byte[] by = new byte[1024];int len = by.length;DatagramPacket dp = new DatagramPacket(by,len);while(true){// 接收数据包try {ds.receive(dp);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}// 处理数据包并显示byte[] by2 = dp.getData();int length = dp.getLength();String s = new String(by2,0,length);String ip = dp.getAddress().getHostAddress();System.out.println(ip +":"+s);}}}


聊天室(同一个窗口实现发收消息):

package netDemo;import java.net.DatagramSocket;import java.net.SocketException;public class ChatRoom { public static void main(String[] args) throws SocketException { SendThread st = new SendThread(new DatagramSocket());ReceiveThread rt = new ReceiveThread(new DatagramSocket(8888));Thread t1 = new Thread(st);Thread t2 = new Thread(rt);t1.start();t2.start();}}


TCP协议发送和接收数据(Socket)

TCP发送demo(客户端):

package netDemo;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.Socket;import java.net.UnknownHostException;public class TcpClientDemo {public static void main(String[] args) throws UnknownHostException, IOException { // 创建Socket对象 Socket s = new Socket("192.168.1.106",9999); // 获得输出流对象         OutputStream os = s.getOutputStream();         // 给服务器发数据                  os.write("hello tcp".getBytes());                 // 得到输入流对象         InputStream is = s.getInputStream();                  // 接收服务端的返回消息          byte[] bys = new byte[1024];          int len = is.read(bys);          String str = new String(bys,0,len);          System.out.println(str);                   // 释放资源         s.close();}}


TCP接收demo(服务端):

package netDemo;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket; /**  * 1 创建服务端Socket对象  * 2 监听客户端连接  * 3 获得输入流对象  * 4 读取数据并处理  */ public class TcpServerDemo { public static void main(String[] args) throws IOException { // 创建服务端Socket对象 ServerSocket ss = new ServerSocket(9999); // 监听客户端连接 Socket s = ss.accept(); // 得到输入流对象 读取数据 InputStream is = s.getInputStream(); byte[] b = new byte[1024]; int len = is.read(b);         String str = new String(b,0,len);         System.out.println(str);         // 得到输出流对象          OutputStream os = s.getOutputStream();         // 给客户端返回状态         os.write("发送成功".getBytes());         s.close();}}

上面的demo灵活运用,我们可以实现很多功能,比如,客户端从文件读取内容,服务端把接收到的内容存入文件,我们就可以实现文件上传。服务端运用多线程,我们可以实现多个客户端同时上传并且互不影响。



阅读全文
0 0