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

所属分类: 软件编程 / C#教程 阅读数: 62
收藏 0 赞 0 分享

本文使用的开发环境是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工具实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

C#使用oledb读取excel表格内容到datatable的方法

这篇文章主要介绍了C#使用oledb读取excel表格内容到datatable的方法,涉及C#操作oledb及datatable的相关技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

C#使用oledb操作excel文件的方法

这篇文章主要介绍了C#使用oledb操作excel文件的方法,涉及C#中oledb操作excel的相关技巧,非常具有实用价值,需要的朋友可以参考下
收藏 0 赞 0 分享

C#使用IHttpModule接口修改http输出的方法

这篇文章主要介绍了C#使用IHttpModule接口修改http输出的方法,涉及C#操作IHttpModule接口的相关技巧,非常具有实用价值,需要的朋友可以参考下
收藏 0 赞 0 分享

C#给图片加水印的简单实现方法

这篇文章主要介绍了C#给图片加水印的简单实现方法,涉及C#操作图片的相关技巧,非常具有实用价值,需要的朋友可以参考下
收藏 0 赞 0 分享

C#生成随机数的方法小结

这篇文章主要介绍了C#生成随机数的方法,实例总结了C#生成随机数的相关技巧,非常具有实用价值,需要的朋友可以参考下
收藏 0 赞 0 分享

C#使用jQuery实现无刷新评论提交的方法

这篇文章主要介绍了C#使用jQuery实现无刷新评论提交的方法,涉及C#结合jQuery进行Ajax操作的相关技巧,非常具有实用价值,需要的朋友可以参考下
收藏 0 赞 0 分享

C#读取中文文件出现乱码的解决方法

这篇文章主要介绍了C#读取中文文件出现乱码的解决方法,涉及C#中文编码的操作技巧,非常具有实用价值,需要的朋友可以参考下
收藏 0 赞 0 分享

C#图像对比度调整的方法

这篇文章主要介绍了C#图像对比度调整的方法,涉及C#实现图像对比度操作的相关技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

C#图像灰度级拉伸的方法

这篇文章主要介绍了C#图像灰度级拉伸的方法,涉及C#灰度操作的相关技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

C#图像线性变换的方法

这篇文章主要介绍了C#图像线性变换的方法,涉及C#操作图像线性变换的相关技巧,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多