问答详情
源自:4-3 编程实现基于 UDP 的 Socket 通信之客户端

老师,我写了UDP的多线程实现,但是抛出了很多异常,不知道怎么解决~

//这是UdpThread类

import java.io.IOException;

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.InetAddress;


public class UdpThread extends Thread{

DatagramSocket socket=null;

DatagramPacket packet=null;

byte[] data=new byte[1024];

public UdpThread(DatagramSocket socket,DatagramPacket packet,byte[] data){

this.socket=socket;

this.packet=packet;

this.data=data;

}

public void run(){

DatagramPacket packet=new DatagramPacket(data, data.length);

String info=new String(data, 0, packet.getLength());

System.out.println("I'm the Server,The Client said:"+info);

InetAddress address=packet.getAddress();

int port =packet.getPort();

byte[] data2="Welcome!!".getBytes();

DatagramPacket packet2=new DatagramPacket(data2, data2.length, address, port);

try {

socket.send(packet2);

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

socket.close();

}

}

//这是UdpServer类


import java.io.IOException;

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.InetAddress;

import java.net.SocketException;


public class UdpServer {


public static void main(String[] args) throws IOException {

DatagramSocket socket=new DatagramSocket(8080);//实例化DatagramSocket,指定8080端口

byte[] data=new byte[1024];

DatagramPacket packet=new DatagramPacket(data, data.length);

System.out.println("服务器已经启动");

int count=0;

while(true){

socket.receive(packet);

UdpThread thread=new UdpThread(socket,packet,data);

thread.start();

count++;

System.out.println("当前连接的客服端有:"+count+"个。");

}

}


}

//这是UdpClient类

import java.io.IOException;

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.InetAddress;

import java.net.SocketException;

import java.net.UnknownHostException;


public class UdpClient {


public static void main(String[] args) throws IOException {

InetAddress address=InetAddress.getByName("localhost");

int port=8080;

byte[] data="username:admikn;password:orange".getBytes();//创建地址,端口,字节

DatagramPacket packet=new DatagramPacket(data, data.length, address, port);//实例化DatagramPacket

DatagramSocket socket=new DatagramSocket();//实例化DatagramSocket

socket.send(packet);//发送数据报

byte[] data2=new byte[1024];

DatagramPacket packet2=new DatagramPacket(data2,data2.length);

socket.receive(packet2);

String reply=new String(data2, 0, packet2.getLength());

System.out.println("The server said:"+reply);

socket.close();

}


}


提问者:微笑彡三色 2015-02-04 13:20

个回答

  • 汤小洋
    2015-02-10 14:38:33

    把异常信息贴下呢

  • Moon丨灬下弦
    2016-06-22 16:19:44

    吧thread类里面的socket.close()删掉

  • 逃跑的乌贼
    2015-09-30 13:40:12

    和我一样的问题……请问您解决了没有?似乎是packet传到线程里的时候就是null了