TCP通信(一)——同步连接

来源:互联网 发布:newsql数据库哪个最好 编辑:程序博客网 时间:2024/06/05 13:33

这篇博客主要包含两个部分的内容:一个是服务端的代码,一个是客户端的代码。
一、服务端类

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Net.Sockets;using System.Net;namespace TCPServer{    class Program    {        private const int portNum = 1999;        static void Main(string[] args)        {            TcpListener listener = new TcpListener(IPAddress.Any, portNum);            listener.Start();            bool isDone = false;            while(!isDone)            {                TcpClient client = listener.AcceptTcpClient();                if(client!=null)                {                    NetworkStream stream = client.GetStream();                    byte[] bytes = Encoding.ASCII.GetBytes(DateTime.Now.ToString());                    try                    {                        stream.Write(bytes, 0, bytes.Length);                        stream.Close();                        client.Close();                    }                    catch(Exception e)                    {                        Console.WriteLine(e.ToString());                    }                }            }            listener.Stop();        }    }}

服务端代码说明:
1、端口号,即告诉客户端我哪间屋子是敞开的。关于这句代码,还是要多说几句的:

TcpListener listener = new TcpListener(IPAddress.Any, portNum);

IPAddress.Any是代表任意地址的意思,即:0.0.0.0
IPAddresss.Loop是代表本机,也就是:127.0.0.1
所以这个构造函数的意思是,要传递一个ip地址,以及以端口号。早期的C#提供的API,只需要端口号,但是已经标记过时了。所以,你这里既可以填写本机地址,也可以填写某个特定的IP。比如192.168.1.123等等,如果是字符串的话,那么则需要用下面的函数转换一下。

TcpListener listener = new TcpListener(IPAddress.Parse("191.168.1.123"),portNum);

这样就可以了。
2、然后开始监听:
这里写图片描述
3、循环监听是否有客户端连接进来。故有一个while死循环。
4、当有一个客户端连接的时候,则后去流,然后向管道中写入当前系统时间,紧接着就关闭连接。

二、客户端

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Net.Sockets;using System.Text;namespace TCPClient{    class Program    {        private const string hostName = "127.0.0.1";        private const int portNum = 1999;        static void Main(string[] args)        {            try            {                TcpClient client = new TcpClient(hostName, portNum);                NetworkStream stream = client.GetStream();                byte[] bytes = new byte[1024];                int bytesRead = stream.Read(bytes, 0, bytes.Length);                Console.WriteLine(Encoding.ASCII.GetString(bytes, 0, bytes.Length));                client.Close();            }            catch(Exception e)            {                Console.WriteLine("网络异常!");            }        }    }}

客户端代码说明:
1、首先指定要连接的服务器的地址和端口,建立连接。
2、然后获取流,读取服务端传过来的字节。

运行说明:
1、先运行服务端,然后运行客户端,你会发现客户端程序的控制台窗口,收到了,一个日期字符串。

扩展:
关于windows下的端口监听查看,我们可以使用如下的命令:netstat -ano命令。
这里写图片描述

over!!!

0 0
原创粉丝点击