我能够通过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);
}
}
}
答案 0 :(得分:1)
在telnet中,数据在您键入时发送,但您只有在按下 enter 键后才会收到响应。我敢打赌txtMessage.Text
不包含换行符或其他终止消息。
答案 1 :(得分:0)
Read
可以返回任意数量的字节。返回值表示读取了多少。它不一定会一次读取所有字节。您需要在循环中读取,直到读取完所有字节为止。