c# TcpClient简易聊天工具

2021-04-19 02:27

阅读:425

说明: 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 和端口 点击链接 就可以了

写的比较急,就不多说了

 


评论


亲,登录后才可以留言!