C# 我的TCP客户端未连接到我的TCP服务器
这是我在C#中通过TCP进行客户机-服务器通信的第一步。“等待客户端…”消息后服务器被卡住。客户端显示“错误:未连接到服务器”。怎么了 服务器代码:C# 我的TCP客户端未连接到我的TCP服务器,c#,tcpclient,tcpserver,C#,Tcpclient,Tcpserver,这是我在C#中通过TCP进行客户机-服务器通信的第一步。“等待客户端…”消息后服务器被卡住。客户端显示“错误:未连接到服务器”。怎么了 服务器代码: using System; using System.Net; using System.Net.Sockets; namespace MyTCPServer { public class MyTCPServerClass { public static void Main(string[] args)
using System;
using System.Net;
using System.Net.Sockets;
namespace MyTCPServer
{
public class MyTCPServerClass
{
public static void Main(string[] args)
{
TcpListener listener = null;
int servPort = 55437;
try
{
listener = new TcpListener(IPAddress.Any, servPort);
listener.Start();
}
catch (SocketException se)
{
Console.WriteLine(se.ErrorCode + ": " + se.Message);
Environment.Exit(se.ErrorCode);
}
TcpClient client = null;
NetworkStream netStream = null;
try
{
Console.WriteLine("Waiting for Client...");
client = listener.AcceptTcpClient();
Console.WriteLine("Get Stream...");
netStream = client.GetStream();
Console.Write("Handling client - ");
int bytesRcvd;
int totalBytesEchoed = 0;
byte[] rcvBuffer = new byte[10000];
while ((bytesRcvd = netStream.Read(rcvBuffer, 0, rcvBuffer.Length)) > 0)
{
netStream.Write(rcvBuffer, 0, bytesRcvd);
totalBytesEchoed += bytesRcvd;
}
Console.WriteLine("echoed {0} bytes.", totalBytesEchoed);
netStream.Close();
client.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
netStream.Close();
}
}
}
}
客户端代码:
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;
namespace MyTCPClient
{
/// <summary>
/// Demonstration eines synchron agierenden TcpClienten.
/// </summary>
public class MyTCPClientClass
{
static void Main(string[] args)
{
byte[] byteBuffer = Encoding.ASCII.GetBytes("Hello World");
//IPAddress ipAddress = IPAddress.Parse("192.168.1.16");
IPAddress ipAddress = IPAddress.Loopback;
int servPort = 55437;
TcpClient client = null;
NetworkStream netStream = null;
try {
client = new TcpClient(new IPEndPoint(ipAddress, servPort));
if (!client.Connected)
{
Console.WriteLine("Error: Not Connected to server");
throw new Exception();
}
else Console.WriteLine("Connected to server... sending echo string");
netStream = client.GetStream();
netStream.Write(byteBuffer, 0, byteBuffer.Length);
Console.WriteLine("Sent {0} bytes to server...", byteBuffer.Length);
int totalBytesRcvd = 0;
int bytesRcvd = 0;
while (totalBytesRcvd < byteBuffer.Length) {
if ((bytesRcvd = netStream.Read(byteBuffer, totalBytesRcvd,
byteBuffer.Length - totalBytesRcvd)) == 0) {
Console.WriteLine("Connection closed prematurely.");
break;
}
totalBytesRcvd += bytesRcvd;
}
Console.WriteLine("Received {0} bytes from server: {1}", totalBytesRcvd,
Encoding.ASCII.GetString(byteBuffer, 0, totalBytesRcvd));
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally {
if (netStream != null) netStream.Close();
if (client != null) client.Close();
}
Console.ReadKey(true);
}
}
}
使用系统;
使用System.IO;
Net系统;
使用系统文本;
使用System.Net.Sockets;
命名空间MyTCPClient
{
///
///演示是同步的。
///
公共类MyTCPClientClass
{
静态void Main(字符串[]参数)
{
byte[]byteBuffer=Encoding.ASCII.GetBytes(“Hello World”);
//IPAddress=IPAddress.Parse(“192.168.1.16”);
IPAddress IPAddress=IPAddress.Loopback;
int servPort=55437;
TcpClient client=null;
NetworkStream netStream=null;
试一试{
client=newtcpclient(newipendpoint(ipAddress,servPort));
如果(!client.Connected)
{
Console.WriteLine(“错误:未连接到服务器”);
抛出新异常();
}
else Console.WriteLine(“连接到服务器…发送回显字符串”);
netStream=client.GetStream();
Write(byteBuffer,0,byteBuffer.Length);
WriteLine(“已将{0}字节发送到服务器…”,byteBuffer.Length);
int totalBytesRcvd=0;
int bytesRcvd=0;
while(总字节数小于字节缓冲长度){
如果((bytesRcvd=netStream.Read)(byteBuffer,totalBytesRcvd,
byteBuffer.Length-totalBytesRcvd))==0){
WriteLine(“连接过早关闭”);
打破
}
totalBytesRcvd+=bytesRcvd;
}
WriteLine(“从服务器接收到{0}字节:{1}”,totalBytesRcvd,
Encoding.ASCII.GetString(byteBuffer,0,totalBytesRcvd));
}
捕获(例外e)
{
控制台写入线(e.Message);
}
最后{
如果(netStream!=null)netStream.Close();
如果(client!=null)client.Close();
}
Console.ReadKey(true);
}
}
}
client=newtcpclient();
Connect(新的IPEndPoint(ipAddress,servPort));
就是这样。但为什么,我认为连接会自动建立,因为地址和端口已经在构造函数中传递了…@oliver,这是非常不同的;阅读这里“备注”的结尾:嗯,这很奇怪,因为Connect没有没有没有参数的重载。所以它需要地址+端口,但我已经将其传递给构造函数(需要调用Connect…)。所以有一个接受地址+端口的构造函数是没有实际意义的,对吗?或者我遗漏了什么?顺便说一下:这不是任何“真正的”TCP服务器的编写方式,主要是因为它可以扩展到一个客户端,或者每个客户端使用线程(同样不可扩展);“好的”TCP服务器的代码要么极其复杂(缓冲池、共享工作者等),要么使用替代API为您隐藏所有这些;如果有兴趣的话,我很乐意提供建议——如果这只是一个例子,可能就不需要了。我真正的观点是:不要把这个例子当回事:没有人会用这种方式编写TCP服务器。这就是一个例子。我很乐意接受您对上述主题的建议。好吧,如果我今天要编写一个TCP服务器,我会从“Kestrel”作为底层服务器开始,它使用“pipelines”API;从这里开始进行长时间的讨论(包括示例和github的链接等):