以下是用c#编写的示例服务器程序,它从客户端接收id。我的示例代码如下。我想将一个字符串数组发送到客户端,并在客户端控制台上显示。 示例数组字符串可以是:
string[] arr1 = new string[] { "one", "two", "three" };
我需要使用以下服务器和客户端代码添加哪些其他代码?
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace server
{
class Program
{
static void Main(string[] args)
{
TcpListener tcpListener = new TcpListener(IPAddress.Any, 1234);
tcpListener.Start();
while (true)
{
TcpClient tcpClient = tcpListener.AcceptTcpClient();
byte[] data = new byte[1024];
NetworkStream ns = tcpClient.GetStream();
int recv = ns.Read(data, 0, data.Length);
string id = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine(id);
}
}
}
}
答案 0 :(得分:0)
由于Tcp是基于流的协议,我建议你使用更高级别的普通byte[]
。如果您只需要从客户端向服务器发送字符串,反之亦然,我认为两端的StreamReader
和StreamWriter
都可以正常工作。在StreamWriter
方面,您已获得WriteLine(string)
方法发送给客户,StreamReader
方法类似ReadLine()
。
以下是您可以应用于模型的简化:
服务器端:
TcpClient client; //Let's say it's already initialized and connected properly
StreamReader reader = new StreamReader(client.GetStream());
while(client.Connected)
{
string message = reader.ReadLine(); //If the string is null, the connection has been lost.
}
客户方:
TcpClient client; //Same, it's initialized and connected
StreamWriter writer = new StreamWriter(client.GetStream());
writer.AutoFlush = true; //Either this, or you Flush manually every time you send something.
writer.WriteLine("My Message"); //Every message you want to send
StreamWriter
将以新行结束每条消息,以便StreamReader
知道何时收到完整字符串。
请注意,TCP连接是全双工连接。这意味着您可以同时发送和接收数据。如果要实现类似的功能,请查看WriteLineAsync(string)
和ReadLineAsync()
方法。
如果要发送数组,请建立一个简单的协议,如下所示:
writer.WriteLine(myArray.Length.ToString);
for
循环中接收所有字符串。收到所有字符串后,请重复此过程。
答案 1 :(得分:0)
将字符串数组发送到客户端
TcpListener tcpListener = new TcpListener(IPAddress.Any, 1234);
tcpListener.Start();
while (true)
{
TcpClient tcpClient = tcpListener.AcceptTcpClient();
byte[] data = new byte[1024];
NetworkStream ns = tcpClient.GetStream();
string[] arr1 = new string[] { "one", "two", "three" };
var serializer = new XmlSerializer(typeof(string[]));
serializer.Serialize(tcpClient.GetStream(), arr1);
tcpClient.GetStream().Close()
tcpClient.Close();
int recv = ns.Read(data, 0, data.Length);
in this line
string id = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine(id);
}
}
客户端
try
{
byte[] data = new byte[1024];
string stringData;
TcpClient tcpClient = new TcpClient("127.0.0.1", 1234);
NetworkStream ns = tcpClient.GetStream();
var serializer = new XmlSerializer(typeof(string[]));
var stringArr = (string[])serializer.Deserialize(tcpClient.GetStream());
foreach (string s in stringArr)
{
Console.WriteLine(s);
}
string input = Console.ReadLine();
ns.Write(Encoding.ASCII.GetBytes(input), 0, input.Length);
ns.Flush();
}
catch (Exception e)
{
Console.Write(e.Message);
}
Console.Read();