使用TCP的HelloServer

HelloServer是一个在1234端口监听的服务端程序,它接受客户送来的数据,而且把这些数据解释为响应的ASCII字符,再对客户作出相似“Hello,...!"这样的响应。如下是HelloServer的代码。服务器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace HelloServer
{
    class Program
    {
        static void Main(string[] args)
        {
            string host = "localhost";
            IPAddress ip = Dns.Resolve(host).AddressList[0];
            int port = 1234;
            TcpListener lst = new TcpListener(ip,port);
            //开始监听
            lst.Start();

            //进入等待客户的无限循环
            while (true)
            {
                Console.Write("等待链接。。。。");
                TcpClient c = lst.AcceptTcpClient();

                Console.WriteLine("客户已链接");
                NetworkStream ns = c.GetStream();
                //获取客户发来的数据
                byte [] request = new byte[512];
                int bytesRead = ns.Read(request, 0, request.Length);
                string input = Encoding.ASCII.GetString(request, 0, bytesRead);

                Console.WriteLine("客户请求:{0}",input);
                
                //构造返回数据
                string output = "Hello, " + input + "!";
                byte[] hello = Encoding.ASCII.GetBytes(output);
                try
                {
                    ns.Write(hello,0,hello.Length);
                    ns.Close();
                    c.Close();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }
            lst.Stop();
        }
    }
}

编译以后运行,程序会显示以下:spa

输出结果code

等待链接。。。。blog

这时服务程序已经进入了等待链接的循环。若是不关闭控制台端口,这个程序会一直等待。ip

如今编写客户端程序HelloClient,客户端代码以下input

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;

namespace HelloClient
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string host = "localhost";
                int port = 1234;
                TcpClient c = new TcpClient(host,port);
                NetworkStream ns = c.GetStream();
                //构造请求数据
                string output = "reader";
                byte[] name = Encoding.ASCII.GetBytes(output);
                ns.Write(name,0,name.Length);
                byte [] response = new byte[1024];
                //读取服务器响应
                int bytesRead = ns.Read(response, 0, response.Length);
                Console.WriteLine(Encoding.ASCII.GetString(response,0,bytesRead));
                c.Close();
            }
            catch (Exception e)
            {
                
                Console.WriteLine(e.ToString());
            }
        }
    }
}

输出结果string

Hello,Reader!it

而在服务端,输出变成了io

输出结果编译

等待链接。。。。客户已链接

客户请求:Reader

等待链接。。。。

 

记住先开启服务端,在开启客户端的请求。否则会报错!

截图看运行结果

相关文章
相关标签/搜索