TCP c/s模式實現點對點,一對多聊天 識別不同的TCP通道.給相應的TCP客戶發送資訊

來源:互聯網
上載者:User

用戶端:

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

namespace mytcpchat
{
    public partial class Form1 : Form
    {
        private Thread th;
        Socket c;
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
          
        }
         public void Client()
        {
            try
            {
                IPEndPoint ServerIPEP = new IPEndPoint(IPAddress.Parse(this.comboBox1.Text.Trim()), 5656);
                c = new Socket(ServerIPEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                c.Connect((EndPoint)ServerIPEP);
                c.Send(System.Text.Encoding.Default.GetBytes(this.sendmessage.Text.Trim()));
                byte[] data = new byte[2048];
                while (true)
                {
                    int rect = c.Receive(data);
                    byte[] chat = new byte[rect];
                    Buffer.BlockCopy(data, 0, chat, 0, rect);
                    this.message.AppendText(System.Text.Encoding.Default.GetString(chat));
                }
           }
            catch (Exception ex)
            {
              //  MessageBox.Show(ex.Message);
            }

        }

        private void button1_Click(object sender, EventArgs e)
                    {
                        try
                        {

                            th = new Thread(new ThreadStart(Client));//建立一個用於監聽的線程
                            th.Start();//開啟新線程
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }
        }
    }

服務端:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Collections;
namespace mytcpserver
{
    public partial class Form1 : Form
    {
        Socket s;
        IPEndPoint ServerIPEP;
        private Thread th;
        Socket uc;
        private ArrayList alSock;//
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }
         public void  Server()
        {
            int port = 5656;
            
            ServerIPEP = new IPEndPoint(IPAddress.Any, port);
            s = new Socket(ServerIPEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            s.Bind((EndPoint)ServerIPEP);
            s.Listen(10);
            alSock = new ArrayList();
            while (true)
            {
                try
                {
                    uc = s.Accept();
                    alSock.Add(uc);
                    this.textBox1.AppendText(System.Convert.ToString(uc));
                    byte[] data = new byte[2048];
                    int rect = uc.Receive(data);
                    byte[] chat = new byte[rect];
                    Buffer.BlockCopy(data, 0, chat, 0, rect);
                    this.mymessage.AppendText("["+uc.RemoteEndPoint.ToString() +"]"+ System.Text.Encoding.Default.GetString(chat));
                             
                }
                catch (Exception ex)
                {
                 //   MessageBox.Show(ex.Message);
                }
            }
        }
        private void Form1_Load(object sender, EventArgs e)
        {
         
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.button1.Enabled = false;
            this.button2.Enabled = true;
            th = new Thread(new ThreadStart(Server));//建立一個用於監聽的線程
            th.Start();//開啟新線程
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                this.button2.Enabled = false;
                this.button1.Enabled = true;
                s.Close();
                th.Abort();//終止線程
                
            

            }
            catch (Exception ex)
            {
               // MessageBox.Show(ex.Message);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (uc == null)
            {
                MessageBox.Show("你不能和任何人進行聊天,請告訴伺服器進行聊天請求");
            }
            else
            {
                int index = int.Parse(this.textBox2.Text.Trim());
                Socket sc = (Socket)alSock[index];
                //發送資料
              sc.Send(System.Text.Encoding.Default.GetBytes(this.answermessage.Text.Trim()));
            }

        }
    }
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.