发送端线程:- import java.io.*;
- import java.net.*;
- public class Send extends Thread{
- private DatagramSocket socket;
- public Send(DatagramSocket socket)
- {
- this.socket=socket;
- }
- @Override
- public void run()
- {
- try {
- BufferedReader br=new BufferedReader(new FileReader("E:/TestIP.java"));
- String line=null;
- while((line=br.readLine())!=null)
- {
- byte[] buf=line.getBytes();
- DatagramPacket packet=new DatagramPacket(buf,buf.length,InetAddress.getByName("127.0.0.1"),10009);
- socket.send(packet);
- }
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
复制代码 接收端线程:- import java.io.*;
- import java.net.*;
- public class Receive extends Thread {
- private DatagramSocket socket;
- public Receive(DatagramSocket socket)
- {
- this.socket=socket;
- }
- @Override
- public void run()
- {
- byte[] buf=new byte[1024];
- DatagramPacket packet=new DatagramPacket(buf,buf.length);
- try {
- socket.receive(packet);
- BufferedWriter bw=new BufferedWriter(new FileWriter("E:/aaa.txt"));
-
- String data=null;
- data=new String(packet.getData());
- for(int i=0;i<packet.getLength();i++)
- {
- bw.write(data);
- bw.newLine();
- bw.flush();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
复制代码 测试类:- import java.net.DatagramSocket;
- import java.net.SocketException;
- public class TsetUDP {
- public static void main(String[] args) throws Exception {
- DatagramSocket sendSocket=new DatagramSocket();
- DatagramSocket receiveSocket=new DatagramSocket(10009);
- new Thread(new Send(sendSocket)).start();
- new Thread(new Receive(receiveSocket)).start();
- }
- }
复制代码 目的:(1)从发送端,把文件TestIP.java 发送到接收端
(2)在接收端,接收文件并复制到 aaa.txt 中
现在只有接收端 搞不定
aaa.txt 中只有几行相同的数据,17行 import java.net.*;
哪位大侠帮帮忙。。。。。 |