• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

c#TcpClient简易聊天工具

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

说明: TcpClient 链接是一个比较安全稳定的链接,作为聊天或者是数据稳定传输,是比较合适的,下面的代码测试过,如果你吧他放在公网服务器上,也是可以用的

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Threading;
using System.IO;
using System.Net.Sockets;
using System.Text.RegularExpressions;

namespace ChatsTolls
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        bool b=true;
        private Thread td;
        private TcpListener listenter;
        private NetworkStream ns;
        private StreamWriter sw;
        private StreamReader sr;
        private Socket socket;
        private TcpClient client;

        private void Form1_Load(object sender, EventArgs e)
        {

        }
        private void Run()
        {
            b = false;
            while (true)
            {
                try
                {
                    socket = listenter.AcceptSocket();
                }
                catch (Exception)
                {
                    return;
                }
                label1.Text = "已经连接";
                ns = new NetworkStream(socket);
                sr = new StreamReader(ns); //读取信息
                sw = new StreamWriter(ns); //写入信息

                ClosingFrom();
            }

        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (sw != null && txtWrite.Text != "")
            {
                if (b)
                {
                    sw.WriteLine("ci说:" + txtWrite.Text.Trim());
                    sw.Flush();
                    lisAdd.Items.Add("我说:" + txtWrite.Text.Trim());
                    txtWrite.Clear();
                }
                else
                {
                    sw.WriteLine("zhu说:" + txtWrite.Text.Trim());
                    sw.Flush();
                    lisAdd.Items.Add("我说:" + txtWrite.Text.Trim());
                    txtWrite.Clear();
                }
            }
  
         
        }
        private void ClosingFrom()
        {
            try
            {
                while (1 == 1)
                {
                    string line = null;
                    if ((line = sr.ReadLine()) != null)
                    {
                        lisAdd.Items.Add(line);
                    }
                    else
                    {
                        label1.Text = "已经断开";
                        break;
                    }
                }
            }
            catch (Exception ex)
            {

                label1.Text = "";
            }
            finally
            {
                if (td.ThreadState == ThreadState.Running)
                {
                    sr.Close();
                    sw.Close();
                    ns.Close();
                    if (!b)
                    {
                        socket.Close();
                    }
                    else
                    {
                        client.Close();
                    }
                    listenter.Stop();
                   
                    sw = null;
                    td.Abort();
                }
            }
        }

        private void btnGet_Click(object sender, EventArgs e)
        {
            if (td != null)
            {
                if (td.ThreadState == ThreadState.Running)
                {
                    sr.Close();
                    sw.Close();
                    ns.Close();
                    if (!b)
                    {
                        socket.Close();
                    }
                    else
                    {
                        client.Close();
                    }
                    listenter.Stop();
                    sw = null;
                    td.Abort();
                }
            }
            this.Close();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (td != null)
            {
                if (td.ThreadState == ThreadState.Running)
                {
                    sr.Close();
                    sw.Close();
                    ns.Close();
                    if (!b)
                    {
                        socket.Close();
                    }
                    else
                    {
                        client.Close();
                    }
                    listenter.Stop();
                    sw = null;
                    td.Abort();
                }
            }
        }
   
        private void button1_Click_1(object sender, EventArgs e)
        {
            if (btnZ.Text =="连 接")
            {
                if (string.IsNullOrEmpty(txtPort.Text))
                {
                    MessageBox.Show("请输入端口号");
                    txtPort.Focus();
                    return;
                } //判断端口号
                if (string.IsNullOrEmpty(txtIp.Text))
                {
                    MessageBox.Show("请输入Ip");
                    txtIp.Focus();
                    return;
                }
                b = true;
                int j = int.Parse(txtPort.Text.Trim());
                string ip = txtIp.Text.Trim();
                //w外网上不能用Dns
                //IPHostEntry ipHost = Dns.GetHostEntry(ip);
                try
                {

                    client = new TcpClient();
                    client.Connect(IPAddress.Parse(ip), j);
                    ns = this.client.GetStream();
                    sr = new StreamReader(ns);
                    sw = new StreamWriter(ns);
                    td = new Thread(new ThreadStart(Runs));
                    td.IsBackground = true;
                    td.Start();
                    label1.Text = "已经连接";
                    btnZ.Text = "断开连接";
                    btnX.Enabled = false;
                }
                catch (Exception ex)
                {

                    label1.Text = "未找到网络";
                }
            }
            else
            {
                if (td != null)
                {

                    try
                    {
                        sr.Close();
                        sw.Close();
                        ns.Close();
                        if (!b)
                        {
                            socket.Close();
                        }
                        else
                        {
                            client.Close();
                        }
                        sw = null;
                        td.Abort();
                    }
                    catch (Exception)
                    {
                        

                    }
                    
                }

                btnX.Enabled = true;
                btnZ.Text = "连 接";
                label1.Text = "";
            }
        }
        private void Runs()
        {
            ClosingFrom();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (btnX.Text == "监 听")
            {
                if (string.IsNullOrEmpty(txtPort.Text))
                {
                    MessageBox.Show("请输入端口号");
                    txtPort.Focus();
                    return;
                } //判断端口号的方法
                b = false;
                int j = int.Parse(txtPort.Text.Trim());
                Control.CheckForIllegalCrossThreadCalls = false;
                listenter = new TcpListener(j); //监听实例化 并写入需要监听的端口
                listenter.Start(); //开始监听
                td = new Thread(new ThreadStart(Run)); //定义线程进行监听
                td.IsBackground = true;
                td.Start(); //线程启动
                btnX.Text = "取消监听";
                btnZ.Enabled = false;
                labJ.Text = "正在监听...";
            }
            else
            {

                try
                {
                    listenter.Stop();
                    td.Abort();
                }
                catch (Exception)
                {

                }
                btnZ.Enabled = true;
                btnX.Text = "监 听";
                labJ.Text = "";
} } } }

 

界面:

首先应在服务器上打开 输入端口号并监听

然后本地输入服务Ip 和端口 点击链接 就可以了

写的比较急,就不多说了

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#自定义时间显示格式发布时间:2022-07-13
下一篇:
C#基础-ref、out发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap