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 += "
" + 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 += "
" + 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;
        }
    }
}
原文地址:https://www.cnblogs.com/summer1987/p/4940438.html