使用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();
        }
    }
}

编译之后运行,程序会显示如下:

输出结果

等待连接。。。。

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

现在编写客户端程序HelloClient,客户端代码如下

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());
            }
        }
    }
}

输出结果

Hello,Reader!

而在服务端,输出变成了

输出结果

等待连接。。。。客户已连接

客户请求:Reader

等待连接。。。。

 

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

截图看运行结果

posted on 2013-11-26 10:54  jianrong.zheng  阅读(443)  评论(0编辑  收藏  举报

导航