這是用c#編寫的一個簡單的服務器代碼。一旦連接到服務器,我想給客戶端一個歡迎消息。歡迎消息將顯示在客戶端的屏幕上。我將如何做到這一點?在c#中向客戶端屏幕發送歡迎消息
部分示例代碼:
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;
using System.Xml.Serialization;
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();
string[] arr1 = new string[] { "one", "two", "three" };
var serializer = new XmlSerializer(typeof(string[]));
serializer.Serialize(tcpClient.GetStream(), arr1);
int recv = ns.Read(data, 0, data.Length); //getting exception in this line
string id = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine(id);
}
}
}
}
什麼是需要修改發送歡迎信息?
你檢查你的NetworkStream變量「NS」有寫法?或者是你可以通過tcpClient.GetStream到StreamWriter類並調用寫入方法 – Viru
可以請你給我一個示例代碼片段? @Viru – ACE