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工具实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • C# lambda表达式应用如何找出元素在list中的索引

    1.先写个规则方法 private bool check(string str){ return str.EndsWith("xxx"); } 2.再写个Predicate Predicate<string> predicate=new Predicate<string>(check)); 如果逻辑不复杂,可以这样写 private void OpenMenu(GameObject gob){ Predicate<string> predicate=

  • C# List实现行转列的通用方案

    最近在做报表统计方面的需求,涉及到行转列报表.根据以往经验使用SQL可以比较容易完成,这次决定挑战一下直接通过代码方式完成行转列.期间遇到几个问题和用到的新知识这里整理记录一下. 阅读目录 问题介绍 动态Linq System.Linq.Dynamic其它用法 总结 问题介绍 以家庭月度费用为例,可以在[Name,Area,Month]三个维度上随意组合进行分组,三个维度中选择一个做为列显示. /// <summary> /// 家庭费用情况 /// </summary> publ

  • C# listview 点击列头排序的实例

    实例如下: #region 自定义变量 int currentCol = -1; bool sort; #endregion//列头点击事件 private void lvw_ColumnClick(object sender, ColumnClickEventArgs e) { string Asc = ((char)0x25bc).ToString().PadLeft(4, ' '); string Des = ((char)0x25b2).ToString().PadLeft(4, ' '

  • C#获取鼠标在listview右键点击单元格的内容方法

    当我们右键点击listview控件时,可以得到选择的项的各个文本内容. 现在我们要求只获取右键点击时的单元格的文本内容. 方法如下: 1.定义全局的鼠标状态 Point m_MBRpt;//鼠标右键点击时Point 2.处理鼠标按下时在listView的消息 private void listView1_MouseDown(object sender, MouseEventArgs e) { // if (e.Button==MouseButtons.Right) { // 得到屏幕鼠标的坐标,

  • C# ListBox中的Item拖拽代码分享

    我们先来看下运行效果图 Form1.cs代码: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System

  • c#中list.FindAll与for循环的性能对比总结

    前言 最近在网上看到一篇文章,里面说到:List<T>.FindAll的效率竟然比for循环还差,下面是文章的截图: 以上就是baidu出来的一篇文章,让我惊诧不已,因为在AI模块我已经使用了很多FindAll.但是,上文的结论是真的吗? 我在上文代码基础上增加了多次测试的代码: 得到了如下结果: .Net2.0, visual studio 执行1,1,10, 100,1000次: .Net4.1, visual studio 执行1,1,10, 100,1000次: Unity 先预处理再

  • C#中List和SortedList的简介

    一.List简介 所属命名空间:System.Collections.Generic public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable List<T>类是ArrayList 类的泛型等效类.该类使用大小可按需动态增加的数组实现 IList<T> 泛型接口. 泛型的好处: 它为使用c#语言编写面

  • C#中数组、ArrayList、List、Dictionary的用法与区别浅析(存取数据)

    前言 在工作中经常遇到C#数组.ArrayList.List.Dictionary存取数据,但是该选择哪种类型进行存储数据,对于初学者的我一直不知道该怎么取舍.于是抽空好好看了下他们的用法和比较,在这里总结下来,后面有需要改进的再更新. 初始化 数组: int[] buff = new int[6]; ArrayList: ArrayList buff = new ArrayList(); List: List<int> buff = new List<int>(); Dictio

  • C#实现泛型List分组输出元素的方法

    本文实例讲述了C#实现泛型List分组输出元素的方法.分享给大家供大家参考,具体如下: 背景:在输出列表时,往往需要按照某一字段进行分组,比如在输出城市列表时,按照首字母进行分组,输出学生列表时,按照年级进行分组,然后再对分组的结果按照其他的字段进行排序. 如存在以下STU学生类,代码如下: public class STU { public int ID { get; set; } public string Name { get; set; } public int Age { get; s

  • C#实现在listview中插入图片实例代码

    C#实现在listview中插入图片实例代码 第一步:在窗体中拖入ListView控件和imageList控件: 第二步:设置imageList控件的Images属性,添加你想要的图片: 第三步:设置ListView控件的SmallImageList.LargeImageList.StateImageList属性为imageList: 第四步:编辑ListView控件项的ImageIndex行为你就会发现图片成功显示出来了! 附:在ListView控件中添加选项的代码 private void

  • C#中WPF ListView绑定数据的实例详解

    C#中WPF ListView绑定数据的实例详解 WPF中ListView用来显示数据十分方便, 我们可以将它分成几个列,每一个列用来显示一条数据,但是又是在一方之中. 那么怎样实现这样的效果的呢,这就要用绑定了. 我们先来看一看他的xmal代码 <ListView Name="receiveList" Grid.Row="0"> <ListView.View> <GridView> <GridView.Columns>

  • C#入门教程之集合ArrayList用法详解

    本文实例讲述了C#入门教程之集合ArrayList用法.分享给大家供大家参考,具体如下: .NET Framework提供了用于数据存储和检索的专用类,这些类统称集合.这些类提供对堆栈.队列.列表和哈希表的支持.大多数集合类实现系统的接口.下面我们主要来讲一下ArrayList. ArrayList是命名空间Systrm.Collections下的一部分,它是使用大小可按需动态增加的数组实现IList接口. ArrayList的容量是ArrayList可以保存的元素数.ArrayList的默认初

  • C# WPF ListView控件的实例详解

    C# WPF ListView控件的实例详解 C#的WPF作为现在微软主流的桌面程序开发平台,相比过去的MFC时代,有了非常多的不同.本人刚从MFC平台转过来,以为可以轻松上手,哪知碰到了很多问题,十分不解.不得不乖乖回去看了本书,再继续回到边左边边学的路上.在这边也推荐<深入浅出WPF>这本书,拿来上手还是极好的. 由于WPF以数据驱动UI的设计理念,很多控件用起来都与之前平台的相差很多,ListView控件算是有代表性的,这是进化的成果.关于该控件的应该,很多参考了这篇博文,如觉本人记述不

  • c# winform treelistview的使用(treegridview)实例详解

    TreeView控件显示的内容比较单一,如果需要呈现更详细信息TreeListView是一个不错的选择. 先看效果: 首先需要引用文件System.Windows.Forms.TreeListView.dll.System.Runtime.InteropServices.APIs.dll 你可以将TreeListView加入到工具箱中然后在添加到窗体中. 1.你需要添加列 2.你需要添加一个ImageList作为节点图标的容器(你还需要配置TreeListView的SmallImageList属

  • C# 字符串、数组和List的截取和转换实例

    如下所示: using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; namespace ConsoleApp1 { class Program { /// <summary> /// 字符串,数组和List的截取,转换 /// </summary> /// <pa

随机推荐