我们有一个Android应用程序,在一个特定的设备上充当服务器。所有其他设备都像客户端一样。
服务器开始在while循环中侦听传入的tcp连接。当收到连接请求时,它会触发一个事件,因此该类的用户可以处理请求,然后调用MyTcpServer类的WriteData方法来响应收入请求。然后关闭连接客户端的networkStream并开始新的循环迭代。
在while循环中接收传入请求然后在将数据发送到客户端后关闭它是一个好习惯吗?
服务器和客户端使用下面列出的相同类:
public class MyTcpServer
{
#region Fields
TcpListener listener;
TcpClient client;
#endregion
#region Properties
public bool IsRunning { get; private set; }
#endregion
#region Protected methods
protected static byte[] StringToBytes(string input)
{
return Encoding.UTF8.GetBytes (input);
}
#endregion
#region Public methods
public void Start(string SERVER_IP, int PORT_NO)
{
if (IsRunning)
return;
IsRunning = true;
Task.Run (() => {
//---listen at the specified IP and port no.---
IPAddress localAdd = IPAddress.Parse (SERVER_IP);
listener = new TcpListener (localAdd, PORT_NO);
Console.WriteLine ("Listening...");
listener.Start ();
while (true) {
client = listener.AcceptTcpClient ();
//---get the incoming data through a network stream---
NetworkStream nwStream = client.GetStream ();
byte[] buffer = new byte[client.ReceiveBufferSize];
//---read incoming stream---
int bytesRead = nwStream.Read (buffer, 0, client.ReceiveBufferSize);
//---convert the data received into a string---
string dataReceived = Encoding.ASCII.GetString (buffer, 0, bytesRead);
var ip = ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString ();
Array.Clear (buffer, 0, buffer.Length);
Console.WriteLine ("[" + DateTime.Now.ToString ("HH:mm:ss") + "] Received : " + dataReceived);
DataReceived?.Invoke (this, new Data () {Stream = nwStream, Message = dataReceived,
IP = ip
});
nwStream.Close();
}
});
}
public void WriteData(NetworkStream nwStream, byte[] responseData)
{
try {
nwStream.Write (responseData, 0, responseData.Length);
} catch (Exception e) {
Console.WriteLine (e.ToString ());
}
}
public void WriteData(string ip, int port, byte[] data)
{
try {
var client = new TcpClient (ip, port);
var nwstream = client.GetStream ();
nwstream.Write (data, 0, data.Length);
nwstream.Close ();
} catch (Exception e) {
Console.WriteLine (e.ToString ());
}
}
public void Stop()
{
if (client != null)
client.Close ();
listener.Stop ();
IsRunning = false;
}
#endregion
public event EventHandler<Data> DataReceived;
public class Data
{
public NetworkStream Stream {get;set;}
public string Message {get;set;}
public string IP {get;set;}
}
}