com.loocme.sys.udp.SocketServer Maven / Gradle / Ivy
package com.loocme.sys.udp;
import com.loocme.sys.util.ThreadUtil;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
@Slf4j
public class SocketServer implements Runnable
{
private int port;
private DatagramSocket server;
private ThreadUtil.ExecutorService workers = null;
private IPackageDeal packageDeal;
private int packageLength;
public SocketServer(int port, int workerNum, int packageLength, IPackageDeal packageDeal)
{
this.port = port;
this.packageDeal = packageDeal;
this.packageLength = packageLength;
if (1024 >= port || 65535 <= port)
{
log.error("the udp server port [" + port + "] outer of range between 1025 and 65524 .");
return;
}
if (null == packageDeal)
{
log.error("the udp server package deal class must not empty .");
return;
}
try
{
server = new DatagramSocket(port);
log.info("start upd server with port [" + port + "] .");
}
catch (SocketException e)
{
log.error("create upd server with port [" + port + "] failed. the reason is : ", e);
server = null;
return;
}
if (0 >= workerNum || 200 < workerNum)
{
log.warn("the udp worker number [" + workerNum + "] outer of range between 1 and 200, reset to 100 .");
workerNum = 100;
}
workers = ThreadUtil.newFixedThreadPool(workerNum);
}
public boolean isInitialSuccess()
{
return null != server;
}
@Override
public void run()
{
while (true)
{
try
{
byte[] b = new byte[packageLength];
DatagramPacket packet = new DatagramPacket(b, packageLength);
this.server.receive(packet);
ServerWorker worker = new ServerWorker(packet, packageDeal);
workers.execute(worker);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy