0
NetworkStreamを介してクライアントからサーバーにバイトを送受信する必要があります。私は文字列と通信する方法を知っていますが、今ではバイトを送受信する必要があります。そのようなサーバークライアントのTCPアプリケーションでbyte []を送受信する
例えば、何か:
static byte[] Receive(NetworkStream netstr)
{
try
{
byte[] recv = new Byte[256];
int bytes = netstr.Read(recv, 0, recv.Length); //(**This receives the data using the byte method**)
return recv;
}
catch (Exception ex)
{
Console.WriteLine("Error!\n" + ex.Message + "\n" + ex.StackTrace);
return null;
}
}
static void Send(NetworkStream netstr, byte[] message)
{
try
{
netstr.Write(message, 0, message.Length);
}
catch (Exception ex)
{
Console.WriteLine("Error!\n" + ex.Message + "\n" + ex.StackTrace);
}
}
サーバー:
private void prejmi_click(object sender, EventArgs e)
{
const string IP = "127.0.0.1";
const ushort PORT = 54321;
TcpListener listener = new TcpListener(IPAddress.Parse(IP), PORT);
listener.Start();
TcpClient client = listener.AcceptTcpClient();
NetworkStream ns = client.GetStream();
byte[] data = Receive(ns)
}
クライアント:
private void poslji_Click(object sender, EventArgs e)
{
const string IP = "127.0.0.1";
const ushort PORT = 54321;
TcpClient client = new TcpClient();
client.Connect(IP, PORT);
string test="hello";
byte[] mybyte=Encoding.UTF8.GetBytes(test);
Send(ns,mybyte);
}
しかし、それはこれを行うにはpropperの方法ではありません、なぜならバイト[ ]データの長さは常に256です。
"サーバー側のデータは常に256の長さになるからです。" - うまくいけば、 'Read'コールからの戻り値は実際に何バイト読み込まれたかを示します。あなたはそれを 'bytes'変数に格納していますが、何もしません。 –