【发布时间】:2011-11-06 03:56:15
【问题描述】:
我有一个服务器应用程序和一个客户端应用程序,其功能已经在工作。让我向您展示如何将我的客户端应用程序连接到我的服务器应用程序:
//SERVER
// instantiate variables such as tempIp, port etc...
// ...
// ...
server = new TcpListener(tempIp, port); //tempIp is the ip address of the server.
// Start listening for client requests.
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[MaxChunkSize];
String data = null;
// Enter the listening loop.
while (disconect == false)
{
Console.Write("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
client = server.AcceptTcpClient(); // wait until a client get's connected...
Console.WriteLine("Connected!");
// Get a stream object for reading and writing
stream = client.GetStream();
// now that the connection is established start listening though data
// sent through the stream..
int i;
try
{
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
// etc..
....
现在在客户端可以说我想建立一个连接然后通过流发送一些数据
//Client
client = new TcpClient(serverIP, port);
// Get a client stream for reading and writing.
stream = client.GetStream();
//then if I wish to send the string hello world to the server I would do:
sendString(stream, "Hello world");
protected void sendString(NetworkStream stream, string str)
{
sendBytes(stream, textToBytes(str));
}
protected void sendBytes(NetworkStream stream, Byte[] data)
{
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
}
protected static Byte[] textToBytes(string text)
{
return System.Text.Encoding.ASCII.GetBytes(text);
}
因为我能够发送字节,所以我能够发送文件或我想要的一切。我使用的技术是,例如,如果我将字符串文件发送到服务器,那么服务器将开始侦听文件。它将打开一个流并将接收到的字节写入该文件。如果发送不同的关键字,服务器将开始侦听不同的方法等。
因此,在处理一台服务器和一台客户端时,一切都很好。现在我想添加更多客户端并需要它们也连接到服务器。我知道可以在同一个端口上建立多个连接,就像我们在网站上使用 por 80 所做的那样......我不知道如何管理多个连接。所以我在想的一件事就是让一切保持原样。如果建立了连接,则告诉服务器启动另一个线程以侦听同一端口上的其他连接。使用这种技术,我将运行多个线程,而且我只知道多线程的基础知识。如果这种技术是我最好的选择,我将开始实施它。你们在那里真的很了解这一切,所以如果有人能指出我正确的方向,那就太好了。或者也许我应该监听几个端口。例如,如果服务器已经连接在端口 7777 上,则不接受来自该端口的连接并开始侦听端口 7778。我的意思是可以有很多不同的方法来实现我需要的东西,你们可能知道最好的方法。我只知道网络的基础知识...
【问题讨论】:
标签: c# networking tcp