![](/img/trans.png)
[英]C# TcpClient and NetworkStream to send/receive data over TCP. Why not using “using” block and can I read data right after writing it to stream?
[英]Why must I every time initialize tcpClient and networkStream to send data to server?
我是C#中網絡編程的新手。
因此,我決定編寫一個簡單的服務器-客戶端Winform應用程序。
我使用TcpListener,TcpClient,NetworkStream。
以下是我從“客戶端應用程序”獲得的代碼片段。
TcpCLient client;
NetworkStream ns;
private void butConnect_Click(object sender, EventArgs e)
{
string remoteIp = txtRemoteIp.Text;
int port = 4848;
client = new TcpClient(remoteIp, port);
ns = client.GetStream();
}
private void butSend_Click(object sender, EventArgs e)
{
string msg = txtMessage.Text;
//string remoteIp = txtRemoteIp.Text;
//int port = 4848;
//client = new TcpClient(remoteIp, port);
//ns = client.GetStream();
byte[] buffer = Encoding.ASCII.GetBytes(msg);
ns.Write(buffer, 0, buffer.Length);
txtMessage.Clear();
}
如您所見,我在butConnect
方法中啟動了client
和ns
。 當我嘗試在butSend
方法中發送某些msg
時,服務器端應用程序無法讀取它。
但是,當我從butsend
方法中的行中刪除注釋時,發送了msg
。
服務器端應用程序可以獲取並顯示客戶端消息。
那是什么問題呢? 為什么我必須再次初始化client
和ns
變量?
這是服務器端代碼。
public FormServer() //this is constructor
{
InitializeComponent();
initControls();
ipAddr = IPAddress.Parse(txtIpAddress.Text);
port = 4848;
listener = new TcpListener(ipAddr, port);
listener.Start();
Thread t = new Thread(Run);
t.Name = "ListenerThread";
t.Start();
}
private void Run()
{
while (true)
{
while (!listener.Pending())
{
Thread.Sleep(200);
}
Action<string> action = (string s) => listStatus.Items.Add(s);
client = listener.AcceptTcpClient();
try
{
NetworkStream ns = client.GetStream();
byte[] buffer = new byte[1024];
ns.Read(buffer, 0, 1024);
string msg = Encoding.ASCII.GetString(buffer);
listStatus.Invoke(action, msg);
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
}
}
}
您創建服務器的方式是每次都等待新連接。 你可以采取
TcpClient client = listener.AcceptTcpClient();
在您的while循環之外。 並且它將按需工作。 否則,您每次都需要連接並發送消息,這沒有錯。 而且,如果您將acceptTcpClient移出循環,則您的服務器將僅適用於一個客戶端。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.