这是一个用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 :(得分: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);