2015-09-27 136 views
0

這是用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); 

      }    
     } 
    } 
} 

什麼是需要修改發送歡迎信息?

+0

你檢查你的NetworkStream變量「NS」有寫法?或者是你可以通過tcpClient.GetStream到StreamWriter類並調用寫入方法 – Viru

+0

可以請你給我一個示例代碼片段? @Viru – ACE

回答

1

可能是你可以嘗試這樣的事情......

StreamWriter writer = new StreamWriter(tcpClient.GetStream); 
writer.Write("Welcome!"); 

在客戶端,你可以有下面的代碼...

byte[] bb=new byte[100]; 
TcpClient tcpClient = new TcpClient(); 
tcpClient.Connect("XXXX",1234) // xxxx is your server ip 
StreamReader sr = new StreamReader(tcpClient.GetStream(); 
sr.Read(bb,0,100); 


// to serialize an array and send it to client you can use XmlSerializer 

var serializer = new XmlSerializer(typeof(string[])); 
    serializer.Serialize(tcpClient.GetStream, someArrayOfStrings); 
    tcpClient.Close(); // Add this line otherwise client will keep waiting for server to respond further and will get stuck. 

//to deserialize in client side 


    byte[] bb=new byte[100]; 
    TcpClient tcpClient = new TcpClient(); 
    tcpClient.Connect("XXXX",1234) // xxxx is your server ip 
var serializer = new XmlSerializer(typeof(string[])); 
var stringArr = (string[]) serializer.Deserialize(tcpClient.GetStream); 
+0

在客戶端接受這個對應的行會是什麼? @Viru – ACE

+0

發佈您的客戶端代碼..... – Viru

+1

無論如何,我添加了代碼,以顯示如何讀取服務器發送的數據 – Viru

相關問題