我希望我的服务器继续监听同一个客户端。它只听一次客户端。如何继续阅读客户端发送的数据。
sk = new Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp);
sk.Bind(new IPEndPoint(IPAddress.Any, 5000));
sk.Listen(-1);
while (true)
{
try
{
Socket client = sk.Accept();
NetworkStream ns = new NetworkStream(client);
byte[] buffer = new byte[32768];
using (MemoryStream ms = new MemoryStream())
{
while (true)
{
int read = ns.Read(buffer, 0, buffer.Length);
if (read <= 0)
break;
ms.Write(buffer, 0, read);
}
}
MemoryStream msi = new MemoryStream(buffer);
Image returnImage = Image.FromStream(msi);
}
catch (Exception)
{
}
}
答案 0 :(得分:0)
最后我找到了解决这个问题的方法
private void Form1_Load(object sender, EventArgs e)
{
serverSocket = new TcpListener(9361);
clientSocket = default(TcpClient);
Thread listen = new Thread(listenClients);
listen.Start();
}
//this will keep listening the clients
public void listenClients()
{
int counter = 0;
serverSocket.Start();
counter = 0;
while ((true))
{
counter += 1;
clientSocket = serverSocket.AcceptTcpClient();
Thread thread = new Thread(
() => readClient(clientSocket));
thread.Start();
}
}
public void broadcast(Image bmp)
{
pictureBox1.Image = bmp;
} //en
//keep reading the client data
private void readClient(TcpClient inClientSocket)
{
byte[] bytesFrom = new byte[65536];
string dataFromClient = null;
while ((true))
{
try
{
NetworkStream networkStream = inClientSocket.GetStream();
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
MemoryStream ms = new MemoryStream(bytesFrom);
Image returnImage = Image.FromStream(ms);
broadcast(returnImage);
}
catch (Exception ex)
{
}
} //end while
} //end readClint