0

我能够通过 telnet 连接服务器并通过 telnet 接收响应,但如果我通过我的代码执行相同操作,我将无法得到它。我非常确定我的代码是正确的,因为我已经通过在本地创建客户端和服务器对其进行了测试。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Configuration;

namespace ClientSocket
{
    public partial class Client : Form
    {
        System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
        NetworkStream serverStream; 

        public Client()
        {
            InitializeComponent();
        }

        private void Client_Load(object sender, EventArgs e)
        {
            msg("Client Started");
            //clientSocket.Connect(ConfigurationManager.AppSettings["ip"].ToString(), Convert.ToInt16(ConfigurationManager.AppSettings["port"]));
            clientSocket.Connect("172.29.29.6", 7506);
            label1.Text = "Client Socket Program - Server Connected ...";
        }

        public void msg(string mesg)
        {
            textBox1.Text = textBox1.Text + Environment.NewLine + " >> " + mesg;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            NetworkStream serverStream = clientSocket.GetStream();
            byte[] outStream = System.Text.Encoding.ASCII.GetBytes(txtMessage.Text);
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();

            byte[] inStream = new byte[1000768];
            serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
            //serverStream.Read(inStream, 0, 1000768);
            string returndata = System.Text.Encoding.ASCII.GetString(inStream);
            msg("Data from Server : " + returndata);

        }
    }
}
4

2 回答 2

1

在 telnet 中,数据在您键入时发送,但您仅在按下回车键后才会收到响应。我打赌txtMessage.Text不包含换行符或其他终止消息。

于 2013-09-19T08:33:46.160 回答
0

Read可以返回任意数量的字节。返回值表示读取了多少。它不一定会一次读取所有字节。您需要循环读取,直到读取所有字节。

于 2013-09-19T13:29:40.100 回答