疯狂java


您现在的位置: 疯狂软件 >> 新闻资讯 >> 正文

简单的socket使用示例


 

package com.demo.udp;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class UdpSend {
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();// 创建udp服务
byte[] b = "hello wolrd".getBytes();
DatagramPacket dp = new DatagramPacket(b, b.length, InetAddress
.getByName("192.168.0.103"), 10000);// 将数据打包

ds.send(dp);
ds.close();
}
}

class UdpRecieve {
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(10000);// 建立监听10000的服务
byte[] b = new byte[1024];
DatagramPacket dp = new DatagramPacket(b, b.length);// 建立一个1024的数据包

ds.receive(dp);// 将数据接受,封存进数据包内
String ip = dp.getAddress().getHostAddress();// 获取传输文件的ip
String data = new String(dp.getData(), 0, dp.getLength());
System.out.println("ip:" + ip + " " + "data:" + data);
}
}