【发布时间】:2019-06-18 02:20:23
【问题描述】:
我正在研究服务器和多个客户端之间的主从网络关系。 服务器很好,问题是我是 TCP 新手,不知道如何在客户端不知道 ip 的情况下连接到服务器。
如果有人可以重写我的一些代码使其正常工作,我将不胜感激。
服务器
namespace Server
{
class Program
{
static void Main(string[] args)
{
TcpListener listen = new TcpListener(IPAddress.Any, 8001);
TcpClient clientSocket = default(TcpClient);
int counter = 0;
listen.Start();
Console.WriteLine(" >> " + "Server Started");
while (true)
{
counter += 1;
clientSocket = listen.AcceptTcpClient();
HandleClinet client = new HandleClinet();
client.startClient(clientSocket, Convert.ToString(counter));
}
}
}
public class HandleClinet
{
TcpClient clientSocket;
string clNo;
public void startClient(TcpClient inClientSocket, string clineNo)
{
clientSocket = inClientSocket;
clNo = clineNo;
Thread ClientThread = new Thread(DoChat);
ClientThread.Start();
}
private void DoChat()
{
byte[] bytesFrom = new byte[1024];
string dataFromClient = null;
byte[] sendBytes = null;
string serverResponse = null;
while ((true))
{
try
{
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0, 1024);
dataFromClient = Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("\0"));
Console.WriteLine(" >> " + "From client-" + clNo + " " + dataFromClient);
serverResponse = Console.ReadLine();
sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
}
catch (Exception ex)
{
throw;
}
}
}
}
}
客户
namespace Client
{
class Program
{
public static TcpClient tcpclnt = new TcpClient();
static void Main(string[] args)
{
while(true)
{
LoopConnect();
LoopPacket();
tcpclnt.Close();
}
}
private static void LoopPacket()
{
byte[] bytesFrom = new byte[1024];
string dataFromClient = null;
byte[] sendBytes = null;
string serverResponse = null;
while ((true))
{
try
{
NetworkStream networkStream = tcpclnt.GetStream();
serverResponse = "Give me a command!";
sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Read(bytesFrom, 0, 1024);
dataFromClient = Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("\0"));
Console.WriteLine(" >> " + "From server -" + dataFromClient);
networkStream.Flush();
}
catch (Exception ex)
{
throw;
}
}
}
private static void LoopConnect()
{
Console.WriteLine("Connecting.....");
while(true)
{
try
{
tcpclnt.Connect(IPAddress.Any, 8001); // The problem area
break;
}
catch (Exception)
{
Console.Write(".");
}
}
Console.WriteLine("Connected.");
}
}
}
【问题讨论】:
-
附注 - 你的代码有一个严重的问题 -
Read返回它放置在缓冲区中的字节数。你无法保证,即使你请求 1024 字节,而对方已经发送了 1024 字节或更多,它也会向你提供 1024 字节。 -
@Damien_The_Unbeliever 应该是文本应用,这里的包不是问题
-
我们这里不是在讨论数据包。 TCP 提供的全部是双向的无穷无尽的字节流。如果您想要“消息传递”,则由 您 在无穷无尽的字节流上实现它,或者转移到构建在 TCP 之上的更高级别的协议,该协议实现消息传递(可能还有其他事情)你。
标签: c# windows sockets networking tcp