我目前正在 C#(主机)和 Java(客户端)之间编写一个非常简单的 TCP 连接
我正在努力用 Java 接收消息,我找到了一个(在我看来)c# 的好解决方案。我将引用传递给构造函数中的方法,该方法将被保存,稍后如果收到消息,我可以从父类调用此方法。
我想在 Java 中做完全相同的事情,但我不知道怎么做!
最后我想要一个易于使用的类,我如何在java中回调。
服务器代码 (c#)
class Server
{
private TcpListener serverSocket;
private TcpClient clientSocket;
private NetworkStream networkStream;
private Action<string> outRecievedMethod;
private Thread recievingRoutineThread;
public Server(int port, Action<string> outRecievedMethod) {
serverSocket = new TcpListener(IPAddress.Any,port);
clientSocket = default(TcpClient);
serverSocket.Start();
clientSocket = serverSocket.AcceptTcpClient();
networkStream = clientSocket.GetStream();
this.outRecievedMethod = outRecievedMethod;
recievingRoutineThread = new Thread(this.recievingRoutine);
recievingRoutineThread.Start();
}
private void recievingRoutine()
{
while (true)
{
String recievingString = null;
try
{
recievingString = recieve();
}catch (Exception ex) { }
recievingString = recievingString.Replace("\0", "");
if(recievingString != null && recievingString != "")
outRecievedMethod((String)recievingString.Clone());
}
}
private string recieve()
{
byte[] bytesFrom = new byte[65536];
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
return dataFromClient;
}
public void send(string msg)
{...}
public void send(byte[] msgBytes)
{...}
}
一只甜甜圈
相关分类