62,614
社区成员
发帖
与我相关
我的任务
分享
import java.io.*;
import java.net.*;
/**
*UDP Echo Client
*/
public class MainClass1
{
public static void main(String[] args)throws Exception
{
String hostname="localhost";
InetAddress ia=InetAddress.getByName(hostname);
//send thread
SenderThread sender=new SenderThread(ia,1919);
sender.start();
//receive thread
Thread receiver=new ReceiverThread();
receiver.start();
}
}
/**
*Sender Thread
*/
class SenderThread extends Thread
{
private InetAddress server;
private DatagramSocket socket;
private boolean stopped=false;
private int port;
//constructor
public SenderThread(InetAddress address,int prot)throws SocketException
{
this.server=address;
this.port=port;
this.socket=new DatagramSocket();
//this.socket.connect(server,port);//connect the socket 远程地址
}
//stop thread
public void halt()
{
this.stopped=true;
}
//get DatagramSocket
public DatagramSocket getSocket()
{
return this.socket;
}
//void run
public void run()
{
try
{
BufferedReader userInput=new BufferedReader(new InputStreamReader(System.in));
while(true)
{
if(stopped)
return;
String theLine =userInput.readLine();
if(theLine.equals("."))
break;
byte[] data=theLine.getBytes();
DatagramPacket pack=new DatagramPacket(data,data.length,server,port);//构造制定长度数据包,用于发送到指定地址的指定端口
socket.send(pack);
Thread.yield();//指定该线程处于可执行状态
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
/**
*Receiver Thread
*/
class ReceiverThread extends Thread
{
DatagramSocket socket;
private boolean stopped=false;
//constructor
public ReceiverThread()throws SocketException
{
socket=new DatagramSocket(1919);
}
//stop thread
public void halt()
{
this.stopped=true;
}
//run
public void run()
{
byte[] buffer=new byte[65507];
while(true)
{
if(stopped)
return;
DatagramPacket dp=new DatagramPacket(buffer,buffer.length);//create a packet to recieive
try
{
socket.receive(dp);
String s=new String(dp.getData(),0,dp.getLength());//get data
System.out.println(s);
Thread.yield();
}
catch(IOException e)
{
System.err.println(e);
}
}
}
}
DatagramPacket pack=new DatagramPacket(data,data.length,server,port);//构造制定长度数据包,用于发送到指定地址的指
DatagramPacket pack=new DatagramPacket(data,data.length,server,port);//构造制定长度数据包,用于发送到指定地址的指
DatagramPacket pack=new DatagramPacket(data,data.length,server,port);//构造制定长度数据包,用于发送到指定地址的指
//this.socket.connect(server,port);//connect the socket 远程地址
/**