socket實現局域網通信


 

今天實現了一個局域網通信的小例子,上來記錄一下,代碼不成熟,勿拍。

這是我本機客戶端:

這是我虛擬機的客戶端。

我為他們分配了靜態IP,這樣就可以實現局域網通信了。注意代碼中必須把監視線程的IsBackground屬性設置為false,這樣關閉窗口時才可以同時將此線程關閉。

默認是true。

 

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

namespace WinFormChat1
{
    public partial class Form1 : Form
    {
        public static readonly int Socket_Buffer_Len = 8192; // 8k
        string myIP = "172.16.1.48";
        string oppositeIP = "172.16.1.211";
        string nickName = "你叫啥";
        public Form1()
        {
            InitializeComponent();
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            string sendMsg = this.nickName + "" + msgBox.Text;
            //send message
            chatBox.Text += "\r\n" + sendMsg;
            InvokeSocket(sendMsg);


        }
        Thread workSocket = null;
        private void button1_Click(object sender, EventArgs e)
        {
            this.nickName = this.nickName1.Text;
            this.myIP = this.txtMyIP.Text.Trim();
            this.oppositeIP = this.txtOpIP.Text.Trim();
            workSocket = new Thread(new ThreadStart(ThreadSocketWork));
            workSocket.IsBackground = true;
            workSocket.Start();

        }

        private  void ThreadSocketWork()
        {
            //自己IP收信
            IPAddress ip = IPAddress.Parse(myIP);
            Socket m_serverListenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            m_serverListenSocket.Bind(new IPEndPoint(ip, 10035));
            m_serverListenSocket.Listen(100);

            byte[] result = new byte[Socket_Buffer_Len];
            while (true)
            {
                Socket clientSocket = m_serverListenSocket.Accept();
                int iCount = clientSocket.Receive(result);
                if (iCount > 0)
                {
                    string msgRcv = Encoding.UTF8.GetString(result, 0, iCount);
                    this.BeginInvoke(new Action(() => this.chatBox.Text += "\r\n" + msgRcv));
                }
                clientSocket.Shutdown(SocketShutdown.Both);
                clientSocket.Close();
            }
        }

        private bool InvokeSocket(string data)
        {
            //發到對方IP上
            IPAddress ip = IPAddress.Parse(oppositeIP);
            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                clientSocket.Connect(new IPEndPoint(ip, 10035));
            }
            catch (Exception ex)
            {
                //TraceUtility.WriteLine("Failed to connect to socket on {0} : {1}, {2}",
                //    ConfigurationManager.AppSettings["AgentServerIP"], ConfigurationManager.AppSettings["AgentServerPort"], ex.Message);
                return false;
            }

            bool result = true;
            try
            {
                clientSocket.Send(Encoding.UTF8.GetBytes(data));
            }
            catch (System.Exception ex)
            {
                //TraceUtility.WriteLine("Failed to send socket data to {0} : {1}, {2}",
                //    ConfigurationManager.AppSettings["AgentServerIP"], ConfigurationManager.AppSettings["AgentServerPort"], ex.Message);
                result = false;
            }
            clientSocket.Shutdown(SocketShutdown.Both);
            clientSocket.Close();
            return result;
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM