package text;
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 SandDemo implements Runnable {
//发送端
private DatagramSocket s;
SandDemo(DatagramSocket s){
this.s=s;
}
@Override
public void run() {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String line=null;
try {
while((line=br.readLine())!=null){
if(line.equals("886"))
{
break;
}
byte[]by=line.getBytes();
DatagramPacket dp=new DatagramPacket(by, by.length,InetAddress.getByName("lenovo-PC"),10088);
s.send(dp);
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
br.close();
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
package text;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
//接收端
public class JIeShouDEmo implements Runnable {
private DatagramSocket s;
JIeShouDEmo(DatagramSocket s){
this.s=s;
}
public void run() {
while(true){
byte[]by=new byte[1024];
DatagramPacket dp=new DatagramPacket(by, by.length);
try {
s.receive(dp);
String IP=dp.getAddress().getHostAddress();
int pro=dp.getPort();
byte[]bys=dp.getData();
String text=new String(bys,0,dp.getLength());
System.out.println(IP+"--"+pro+"--"+text);
PrintWriter pw=new PrintWriter(new FileWriter("fendo.txt"));
pw.println(text);
pw.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package text;
import java.net.DatagramSocket;
import java.net.SocketException;
public class Threshold {
public static void main(String[] args) throws SocketException {
DatagramSocket d=new DatagramSocket();
DatagramSocket d1=new DatagramSocket(10088);
SandDemo s=new SandDemo(d);
JIeShouDEmo j=new JIeShouDEmo(d1);
Thread t=new Thread(s);
Thread t1=new Thread(j);
t.start();
t1.start();
}
}
从控制台输入的语句,保存在fendo.txt中,每次运行后之前保存的都被覆盖了,怎么样才能不覆盖 |
|