package com.guoke2;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
/** * @author guokewind
* @date 创建时间:2015年6月1日 下午6:28:05
* @version
* @parameter
* @since
* @return */
public class Server {
public static void main(String[] args) {
try {
//1.创建服务器DatagramSocket
DatagramSocket socket=new DatagramSocket(8800);
System.out.println("****服务器已经启动,等待客户端连接");
//2.创建数据包,用于接收客户端发送的数据
while(true){
byte [] data= new byte[1024];
DatagramPacket packet=new DatagramPacket(data, data.length);
//3.接收客户端发送的数据
socket.receive(packet);
ServerThread serverThread=new ServerThread(socket,packet);
serverThread.start();
}
}
catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.guoke2;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
/** * @author guokewind
* @date 创建时间:2015年6月1日 下午7:16:08
* @version
* @parameter
* @since
* @return */
public class ServerThread extends Thread {
private DatagramSocket socket;
private DatagramPacket packet;
/*
* 通过构造方法把套接字和数据包传过来,不要传byte [] data,
* 用packet.getData()体现数据是通过数据包传送过来的
*/
public ServerThread(DatagramSocket socket,DatagramPacket packet){
this.socket=socket;
this.packet=packet;
}
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
try{
byte [] data=packet.getData();//返回数据缓冲区
String info=new String(data,0,packet.getLength());
System.out.println("我是服务器"+Thread.currentThread()+",客户端说:"+info);
InetAddress address =packet.getAddress();//得到主机的地址
int port=packet.getPort();//返回某台远程主机的端口号
byte []data2="欢迎您!".getBytes();
DatagramPacket packet2=new DatagramPacket(data2, data2.length,address,port);//发送data2到主机
socket.send(packet2);
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}