本帖最后由 ~与狼共舞~ 于 2013-5-27 21:59 编辑
- import java.io.IOException;
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;
- import java.net.InetAddress;
- import java.util.Scanner;
- public class TensmitDemo {
- public static void main(String[] args) {
- new Sender().start();
- new Recever().start();
- }
- }
- class Sender extends Thread{
- public void run(){
- try(
- DatagramSocket socket = new DatagramSocket(10000,InetAddress.getByName("127.0.0.1"));
- Scanner scanner = new Scanner(System.in);
-
- ){
-
- byte[] arr = scanner.nextLine().getBytes();
- DatagramPacket pocket = new DatagramPacket(arr,arr.length,InetAddress.getByName("127.0.0.1"),20000);
- socket.send(pocket);
-
- } catch (Exception e) {
-
- e.printStackTrace();
- }
- }
- }
- class Recever extends Thread{
- public void run(){
- try(DatagramSocket socket = new DatagramSocket(20000,InetAddress.getByName("127.0.0.1")))
- {
- DatagramPacket packet = new DatagramPacket(new byte[2048],1024);
-
- while(true){
- socket.receive(packet);
- byte[] arr = packet.getData();
- int len = packet.getLength();
- String ip = packet.getAddress().getHostAddress();
- int port = packet.getPort();
- String s = new String(arr,0,len);
- System.out.println(ip + ":" + port + ":" + s);
- }
- } catch (IOException e) {
-
- e.printStackTrace();
- }
- }
- }
复制代码 为什么我的这个程序不能连续的进行消息的发送?每次必须得重新运行一次才能发送一次消息。 |