2015-09-27 98 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

相关问题