我试图从套接字读取数据,但每当我试图读取整个流时,我的程序都会挂起。没有任何错误或异常。
我可以手动读取4个字节,它会起作用,但我不再知道服务器将发送的数据的确切大小,因此我希望读取整个流。我做错了什么?
它在调用ReadToEnd()时挂起。
Stream input = socket.GetStream();
byte[] request = new byte[5];
input.Write(request, 0, 5); //send request
StreamReader reader = new StreamReader(input);
if (input.CanRead == true)
{
string test = reader.ReadToEnd();
}
您的代码不知道流有多长,它可能还没有结束,所以它将继续阻塞,直到结束为止。以下是服务器和客户端的示例(这绝不是一个健壮的实现),但如果您考虑以下代码,您应该了解如何发送请求和接收响应:
public class Server
{
private readonly Thread _listenThread;
private readonly TcpListener _tcpListener;
public Server()
{
_tcpListener = new TcpListener(IPAddress.Any, 3000);
_listenThread = new Thread(Listen);
_listenThread.Start();
}
private void Listen()
{
var tcpListener = _tcpListener;
if (tcpListener != null)
{
tcpListener.Start();
}
while (true)
{
TcpClient client = _tcpListener.AcceptTcpClient();
Console.Out.WriteLine("Connection Accepted");
Thread clientThread = new Thread(DoWork);
clientThread.Start(client);
}
}
private void DoWork(object client)
{
TcpClient tcpClient = client as TcpClient;
if (tcpClient == null)
{
throw new ArgumentNullException("client", "Must pass client in");
}
using (NetworkStream clientStream = tcpClient.GetStream())
{
byte[] message = new byte[1024];
while (true)
{
Console.Out.WriteLine("Waiting for message");
int bytesRead = clientStream.Read(message, 0, 1024);
if (bytesRead == 0)
{
break;
}
ASCIIEncoding encoder = new ASCIIEncoding();
string received = encoder.GetString(message, 0, bytesRead);
Console.Out.WriteLine(String.Format("Read {0}", received));
if (received.Equals("Hello Server !"))
{
byte[] buffer = encoder.GetBytes("Hello Client!");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
}
}
}
}
你需要一个做类似的客户
static void Main(string[] args)
{
try
{
using (TcpClient clientSock = new TcpClient(IPAddress.Loopback.ToString(), 3000))
{
using (Stream clientStream = clientSock.GetStream())
{
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] helloMessage = encoder.GetBytes("Hello Server !");
clientStream.Write(helloMessage, 0, helloMessage.Length);
clientStream.Flush();
using (StreamReader streamReader = new StreamReader(clientStream))
{
while(true)
{
char[] buffer = new char[1024];
streamReader.Read(buffer,0, 1024);
Console.Out.WriteLine(new string(buffer));
}
}
}
}
Console.ReadLine();
}
catch (Exception)
{
// do something here
throw;
}
}