好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

C#使用TcpListener及TcpClient开发一个简单的Chat工具实例

本文使用的开发环境是vs2017及dotnet4.0,写此随笔的目的是给自己及新开发人员作为参考,

本例子比较简单,使用的是控制台程序开发,若需要使用该软件作为演示,必须先运行服务端,再运行客户端。

因为是首次接触该方面的知识,写得比较简陋,如有更好的建议,请提出,谢谢!

一、编写服务器端代码,如下:

?

using system;

using system.text;

using system.net;

using system.net.sockets;

using system.threading.tasks;

namespace chatserver

{

  class program

  {

   static void main(string[] args)

   {

    bool cancel = false;

    byte[] buffer = new byte[1024];

    string message;

    byte[] messagebytes;

    int count = 0;

    tcplistener tcplistener = new tcplistener(new ipendpoint(ipaddress.any, 13000));

    tcplistener.start();

    console.writeline("waiting for a connection... ");

    tcpclient tcpclient = tcplistener.accepttcpclient();

    console.writeline("connected.");

    networkstream stream = tcpclient.getstream();

   

    task.factory.startnew(() =>

    {

     while ((count = stream.read(buffer, 0, buffer.length)) != 0)

     {

      console.writeline($"{datetime.now:yyyy-mm-dd hh:mm:ss fff} reply from server {tcpclient.client.localendpoint.tostring()}:{encoding.utf8.getstring(buffer, 0, count)}");

     }

    });

     

    task t = task.factory.startnew(() =>

    {

     while(!cancel)

     {

      message = console.readline();

      if (message.toupper() == "y")

      {

       cancel = true;

       return;

      }

      messagebytes = encoding.utf8.getbytes(message);

      stream.write(messagebytes, 0, messagebytes.length);

     }

    });

      

    if (cancel) tcpclient.close();

    

    while (true)

    {

     if (t != null && t.iscompleted) break;

    }

   }

  }

}

二、编写客户端代码,如下:

?

using system;

using system.linq;

using system.text;

using system.net;

using system.net.sockets;

using system.threading;

using system.threading.tasks;

namespace chatclient

{

  class program

  {

   static void main(string[] args)

   {

    bool cancel = false;

    byte[] buffer = new byte[1024];

    string message;

    byte[] messagebytes;

    int count = 0;

    try

    {

     tcpclient tcpclient = new tcpclient(new ipendpoint(dns.gethostentry(dns.gethostname()).addresslist.where(p => p.addressfamily == addressfamily.internetwork).first(), 14000));

     tcpclient.connect(new ipendpoint(ipaddress.parse("192.168.94.26"), 13000));

     networkstream stream = tcpclient.getstream();

    

     task.factory.startnew(() =>

     {

      while ((count = stream.read(buffer, 0, buffer.length)) != 0)

      {

       console.writeline($"{datetime.now:yyyy-mm-dd hh:mm:ss fff} reply from client {tcpclient.client.localendpoint.tostring()}:{encoding.utf8.getstring(buffer, 0, count)}");

      }

     });

     task t = task.factory.startnew(() =>

     {

      while (!cancel)

      {

       message = console.readline();

       if (message.toupper() == "y")

       {

        cancel = true;

        return;

       }

       messagebytes = encoding.utf8.getbytes(message);

       stream.write(messagebytes, 0, messagebytes.length);

       thread.sleep(10);

      }

     });

     if (cancel) tcpclient.close();

    

     while (true)

     {

      if (t != null && t.iscompleted) break;

     }

    }

    catch(exception ex)

    {

     console.writeline(ex.message);

     console.readkey();

    }

    }

  }

}

三、先运行服务端代码,后再另外一台电脑运行客户端代码,效果图如下:

以上这篇c#使用tcplistener及tcpclient开发一个简单的chat工具实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:http://www.cnblogs.com/cncc/p/7891728.html

dy("nrwz");

查看更多关于C#使用TcpListener及TcpClient开发一个简单的Chat工具实例的详细内容...

  阅读:47次