本文为原创文章、源代码为原创代码,如转载/复制,请在网页/代码处明显位置标明原文名称、作者及网址,谢谢!


本文使用的开发环境是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[];
string message;
byte[] messageBytes;
int count = ;
TcpListener tcpListener = new TcpListener(new IPEndPoint(IPAddress.Any, ));
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, , buffer.Length)) != )
{
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, , 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[];
string message;
byte[] messageBytes;
int count = ;
try
{
TcpClient tcpClient = new TcpClient(new IPEndPoint(Dns.GetHostEntry(Dns.GetHostName()).AddressList.Where(p => p.AddressFamily == AddressFamily.InterNetwork).First(), ));
tcpClient.Connect(new IPEndPoint(IPAddress.Parse("192.168.94.26"), ));
NetworkStream stream = tcpClient.GetStream(); Task.Factory.StartNew(() =>
{
while ((count = stream.Read(buffer, , buffer.Length)) != )
{
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, , messageBytes.Length);
Thread.Sleep();
}
});
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工具的更多相关文章

  1. 基于SOUI开发一个简单的小工具

    基于DriectUI有很多库,比如 Duilib (免费) soui (免费) DuiVision (免费) 炫彩 (界面库免费,UI设计器付费,不提供源码) skinui (免费使用,但不开放源码, ...

  2. 如何开发一个简单的HTML5 Canvas 小游戏

    原文:How to make a simple HTML5 Canvas game 想要快速上手HTML5 Canvas小游戏开发?下面通过一个例子来进行手把手教学.(如果你怀疑我的资历, A Wiz ...

  3. 重新想象 Windows 8 Store Apps (64) - 后台任务: 开发一个简单的后台任务

    [源码下载] 重新想象 Windows 8 Store Apps (64) - 后台任务: 开发一个简单的后台任务 作者:webabcd 介绍重新想象 Windows 8 Store Apps 之 后 ...

  4. Cocos2d-x-Lua 开发一个简单的游戏(记数字步进白色块状)

    Cocos2d-x-Lua 开发一个简单的游戏(记数字步进白色块状) 本篇博客来给大家介绍怎样使用Lua这门语言来开发一个简单的小游戏-记数字踩白块. 游戏的流程是这种:在界面上生成5个数1~5字并显 ...

  5. Python开发一个简单的BBS论坛

    项目:开发一个简单的BBS论坛 需求: 整体参考“抽屉新热榜” + “虎嗅网” 实现不同论坛版块 帖子列表展示 帖子评论数.点赞数展示 在线用户展示 允许登录用户发贴.评论.点赞 允许上传文件 帖子可 ...

  6. 作业1开发一个简单的python计算器

    开发一个简单的python计算器 实现加减乘除及拓号优先级解析 用户输入 1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568 ...

  7. django学习-11.开发一个简单的醉得意菜单和人均支付金额查询页面

    1.前言 刚好最近跟技术部门的[产品人员+UI人员+测试人员],组成了一桌可以去公司楼下醉得意餐厅吃饭的小team. 所以为了实现这些主要点餐功能: 提高每天中午点餐效率,把点餐时间由20分钟优化为1 ...

  8. 用Qt写软件系列三:一个简单的系统工具(上)

    导言 继上篇<用Qt写软件系列二:QIECookieViewer>之后,有一段时间没有更新博客了.这次要写的是一个简单的系统工具,需求来自一个内部项目.功能其实很简单,就是查看当前当前系统 ...

  9. 基于node实现一个简单的脚手架工具(node控制台交互项目)

    实现控制台输入输出 实现文件读写操作 全原生实现一个简单的脚手架工具 实现vue-cli2源码 一.实现控制台输入输出 关于控制台的输入输出依然是基于node进程管理对象process,在proces ...

随机推荐

  1. linux_base_commond_two

    1.linux privilege commond a.throught ll commond  can get follow picture d  directory    -  file   l ...

  2. oracle temporary table

    oralce 有两种临时表  a.会话级临时表 b.事物级临时表 A.事物级临时表 语法 create  global temporary table table_name( col1  type1, ...

  3. Python通过future处理并发

    future初识 通过下面脚本来对future进行一个初步了解:例子1:普通通过循环的方式 import os import time import sys import requests POP20 ...

  4. 压缩感知“Hello World”代码初步学习

    压缩感知代码初学 实现:1-D信号压缩传感的实现 算法:正交匹配追踪法OMP(Orthogonal Matching Pursuit)   >几个初学问题   1. 原始信号f是什么?我采集的是 ...

  5. java swing中Timer类的学习

    最近在完成学校课程的java平时作业,要实现一个计时器,包含开始.暂停以及重置三个功能.由于老师规定要用这个timer类,也就去学习了一下,顺便记录一下. 首先呢去查了一下java手册上的东西,发现t ...

  6. 聊聊java基础,int值强制类型转换成byte

    聊聊java基础,int值强制类型转换成byte 知识点:byte.short.char在表达式中会自动提升为int 之前做一个应用时,打印IP地址,因为是用4个byte存储的,所以打印的时候值范围是 ...

  7. Leetcode题解(21)

    62. Unique Paths 题目 分析: 机器人一共要走m+n-2步,现在举个例子类比,有一个m+n-2位的二进制数,现在要在其中的m位填0,其余各位填1,一共有C(m+n-2,m-1)种可能, ...

  8. css基础语法一(选择器与css导入方式)

    页面中,所有的CSS代码,需要写入到<style></style>标签中.style标签的type属性应该选择text/css,但是type属性可以省略. CSS修改页面中的所 ...

  9. SSH服务详解

    第1章 SSH服务 1.1 SSH服务协议说明 SSH 是 Secure Shell Protocol 的简写,由 IETF 网络工作小组(Network Working Group )制定:在进行数 ...

  10. 使用Identity Server 4建立Authorization Server (3)

    预备知识: http://www.cnblogs.com/cgzl/p/7746496.html 第一部分: http://www.cnblogs.com/cgzl/p/7780559.html 第二 ...