- 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.SocketException;
- import java.net.UnknownHostException;
- /**
- * UDP传输
- * 1、建立UDP的socket服务
- * 2、将数据封装成数据包
- * 3、用socket服务发送数据包
- * 4、关闭socket服务
- */
- public class UdpDemo {
- public static void main(String[] args) throws IOException {
- //1、建立UDP的socket服务
- DatagramSocket ds=new DatagramSocket();
- //2、将数据封装成数据包
- BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));
- String line=null;
- while((line=bufr.readLine())!=null){
- if(line.equals("over"))
- break;
- byte[] buf=line.getBytes();
- DatagramPacket dp=new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.107"),1000);
- //3、用socket服务发送数据包
- ds.send(dp);
- //4、关闭socket服务
- ds.close();
- }
- }
- }
复制代码
- import java.io.IOException;
- import java.io.OutputStream;
- import java.net.Socket;
- import java.net.UnknownHostException;
- public class TcpDemo {
- public static void main(String[] args) throws UnknownHostException, IOException {
- Socket sk=new Socket("192.168.1.100",10002);
- OutputStream out=sk.getOutputStream();
- out.write("TCP演示".getBytes());
- sk.close();
- }
- }
复制代码
程序1中DatagramPacket地址参数一定要转成InetAddress,否则出错;而程序2中的Socket地址参数也是要求InetAddress,但是这里不转也没问题啊,为什么? |
|