110,533
社区成员
发帖
与我相关
我的任务
分享
public class Logger
{
private boolean LogEvents;
public final boolean getLogEvents()
{
return LogEvents;
}
public final void setLogEvents(boolean value)
{
LogEvents = value;
}
public Logger()
{
setLogEvents(true);
}
public final void Log(String Text)
{
if (getLogEvents())
{
System.out.println(Text);
}
}
}
public enum ServerStatusLevel
{
Off,
WaitingConnection,
ConnectionEstablished;
public int getValue()
{
return this.ordinal();
}
public static ServerStatusLevel forValue(int value)
{
return values()[value];
}
}
@FunctionalInterface
public interface NewConnectionEventHandler
{
void invoke(String loginName, EventArgs e);
}
@FunctionalInterface
public interface DataReceivedEventHandler
{
void invoke(Object sender, String message, EventArgs e);
}
@FunctionalInterface
public interface DisconnectedEventHandler
{
void invoke(Object sender, EventArgs e);
}
@FunctionalInterface
public interface BroadcastEventHandler
{
void invoke(String message, EventArgs e);
}
public class WebSocketServer implements java.io.Closeable
{
private boolean AlreadyDisposed;
private Socket Listener;
private int ConnectionsQueueLength;
private int MaxBufferSize;
private String Handshake;
private StreamReader ConnectionReader;
private StreamWriter ConnectionWriter;
private Logger logger;
private byte[] FirstByte;
private byte[] LastByte;
private byte[] ServerKey1;
private byte[] ServerKey2;
private java.util.ArrayList<SocketConnection> connectionSocketList = new java.util.ArrayList<SocketConnection>();
private ServerStatusLevel Status;
public final ServerStatusLevel getStatus()
{
return Status;
}
private void setStatus(ServerStatusLevel value)
{
Status = value;
}
private int ServerPort;
public final int getServerPort()
{
return ServerPort;
}
public final void setServerPort(int value)
{
ServerPort = value;
}
private String ServerLocation;
public final String getServerLocation()
{
return ServerLocation;
}
public final void setServerLocation(String value)
{
ServerLocation = value;
}
private String ConnectionOrigin;
public final String getConnectionOrigin()
{
return ConnectionOrigin;
}
public final void setConnectionOrigin(String value)
{
ConnectionOrigin = value;
}
public final boolean getLogEvents()
{
return logger.LogEvents;
}
public final void setLogEvents(boolean value)
{
logger.LogEvents = value;
}
public event NewConnectionEventHandler NewConnection;
public event DataReceivedEventHandler DataReceived;
public event DisconnectedEventHandler Disconnected;
private void Initialize()
{
AlreadyDisposed = false;
logger = new Logger();
setStatus(ServerStatusLevel.Off);
ConnectionsQueueLength = 500;
MaxBufferSize = 1024 * 100;
FirstByte = new byte[MaxBufferSize];
LastByte = new byte[MaxBufferSize];
FirstByte[0] = 0x00;
LastByte[0] = (byte)0xFF;
logger.LogEvents = true;
}
public WebSocketServer()
{
setServerPort(4141);
setServerLocation(String.format("ws://%1$s:4141/chat", getLocalmachineIPAddress()));
Initialize();
}
public WebSocketServer(int serverPort, String serverLocation, String connectionOrigin)
{
setServerPort(serverPort);
setConnectionOrigin(connectionOrigin);
setServerLocation(serverLocation);
Initialize();
}
protected void finalize() throws Throwable
{
Close();
}
public final void close() throws java.io.IOException
{
Close();
}
private void Close()
{
if (!AlreadyDisposed)
{
AlreadyDisposed = true;
if (Listener != null)
{
Listener.Close();
}
for (SocketConnection item : connectionSocketList)
{
item.ConnectionSocket.Close();
}
connectionSocketList.clear();
GC.SuppressFinalize(this);
}
}
public static IPAddress getLocalmachineIPAddress()
{
String strHostName = Dns.GetHostName();
IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
for (IPAddress ip : ipEntry.AddressList)
{
//IPV4
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip;
}
}
return ipEntry.AddressList[0];
}
public final void StartServer()
{
char char1 = (char)65533;
Listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
Listener.Bind(new IPEndPoint(getLocalmachineIPAddress(), getServerPort()));
Listener.Listen(ConnectionsQueueLength);
logger.Log(String.format("聊天服务器启动。WebSocket服务器地址:%1$s, 端口:%2$s",getLocalmachineIPAddress(),getServerPort()));
while (true)
{
Socket sc = Listener.Accept();
if (sc != null)
{
Thread.sleep(100);
SocketConnection socketConn = new SocketConnection();
socketConn.ConnectionSocket = sc;
socketConn.NewConnection += new NewConnectionEventHandler(socketConn_NewConnection);
socketConn.DataReceived += new DataReceivedEventHandler(socketConn_BroadcastMessage);
socketConn.Disconnected += new DisconnectedEventHandler(socketConn_Disconnected);
socketConn.ConnectionSocket.BeginReceive(socketConn.receivedDataBuffer, 0, socketConn.receivedDataBuffer.getLength(), 0, new AsyncCallback(socketConn.ManageHandshake), socketConn.ConnectionSocket.Available);
connectionSocketList.add(socketConn);
}
}
}
private void socketConn_Disconnected(Object sender, EventArgs e)
{
// SocketConnection sConn = sender as SocketConnection;
if (sConn != null)
{
// Send(string.Format("【{0}】离开了聊天室!", sConn.Name));
sConn.ConnectionSocket.Close();
// connectionSocketList.Remove(sConn);
}
}
private void socketConn_BroadcastMessage(Object sender, String message, EventArgs e)
{
if (message.indexOf("login:") != -1)
{
SocketConnection sConn = (SocketConnection)((sender instanceof SocketConnection) ? sender : null);
sConn.Name = message.substring(message.indexOf("login:") + "login:".length());
// message = string.Format("欢迎【{0}】来到聊天室!",message.Substring(message.IndexOf("login:") + "login:".Length));
}
// Send(message);
}
private void socketConn_NewConnection(String name, EventArgs e)
{
if (NewConnection != null)
{
NewConnection(name,EventArgs.Empty);
}
}
public final void Send(String message)
{
for (SocketConnection item : connectionSocketList)
{
if (!item.ConnectionSocket.Connected)
{
return;
}
try
{
if (item.IsDataMasked)
{
DataFrame dr = new DataFrame(message);
item.ConnectionSocket.Send(dr.GetBytes());
}
else
{
item.ConnectionSocket.Send(FirstByte);
item.ConnectionSocket.Send(Encoding.UTF8.GetBytes(message));
item.ConnectionSocket.Send(LastByte);
}
}
catch (RuntimeException ex)
{
logger.Log(ex.getMessage());
}
}
}
}