C# Socket网络通信TCP(关键字:Socket)

简单Socket-Tcp通信

在本文中涉及到通信,仅做简单的通信(服务端接受消息,由客户端发出消息)
如有需要,根据需求可直接copy使用

关键字Socket

需要引用命名空间:

using System.Net;
using System.Net.Sockets;

服务端:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace Socket_TcpServer
{
    class Program
    {
        static void Main(string[] args)
        {
            SocketStart();
        }

        public static byte[] clientMsg = new byte[340];

        /// <summary>
        /// 开启TCP通信
        /// </summary>
        /// <param name="o"></param>
        private static void SocketStart()
        {
            int localPort = 8345;
            Socket[] ClientSocket;       //为客户端建立的SOCKET连接
            Socket socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socketServer.Bind(new IPEndPoint(IPAddress.Any, localPort));            //将服务端绑定本地端口号
            socketServer.Listen(10);            //10 表示最大连接数
            Console.WriteLine("------服务端开启------");
            ClientSocket = new Socket[65535];
            int ClientNumb = 0;
            while (true)
            {
                ClientSocket[ClientNumb] = socketServer.Accept();
                Console.WriteLine("-----SOCKET客户端接入-----");
                ClientSocket[ClientNumb].BeginReceive(clientMsg, 0, clientMsg.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack1), ClientSocket[ClientNumb]);
                ClientNumb++;
            }
        }


        /// <summary>
        /// 接受通信数据
        /// </summary>
        /// <param name="AR"></param>
        public static void ReceiveCallBack1(IAsyncResult AR)
        {
            Socket socket = (Socket)AR.AsyncState;
            try
            {
                int endREC = clientMsg.Length;
                string content = Encoding.GetEncoding("GBK").GetString(clientMsg, 0, endREC);               //将接收到的数据进行转码
                Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss")+"收到客户端"+socket.RemoteEndPoint + "消息 \r\n{0}"+content);
                clientMsg = new byte[clientMsg.Length];
                socket.BeginReceive(clientMsg, 0, clientMsg.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack1), socket);     //运用递归方式重新接收新的数据
            }
            catch (Exception ex)
            {
                //Console.WriteLine(ex.ToString());
                Console.WriteLine("--客户端 "+socket.RemoteEndPoint+" 连接断开-----");
            }
        }
    }
}

客户端:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace Socket_TcpClient
{
    class Program
    {
        static void Main(string[] args)
        {
            string content = "这个测试用的一个TCP连接";
            Socket(content);            //开启socket通信
            Console.ReadKey();
        }

        static void Socket(string content)
        {
            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);    
            clientSocket.Bind(new IPEndPoint(IPAddress.Any, 21310));                     //将客户端端绑定本地端口号
            int remotePort = 8345;
            IPAddress remoteIP = IPAddress.Parse("192.168.11.83");
            IPEndPoint remoteIPEndPoint = new IPEndPoint(remoteIP, remotePort);         //绑定需要连接的远端服务器端口号
            clientSocket.Connect(remoteIPEndPoint);

            try
            {
                byte[] sendBytes = Encoding.ASCII.GetBytes(content);
                clientSocket.Send(sendBytes);
                Console.WriteLine("发送成功!");

            }
            catch
            {
                Console.WriteLine("发送失败!");
            }
        }
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
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; using System.Net.Sockets; namespace 监听 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //第一步 ,创建一个Socket Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //第二步,绑定 //二.1,获取本机的IP地址 IPAddress[] address = Dns.GetHostAddresses(Dns.GetHostName()); //二.2,绑定 serverSocket.Bind(new IPEndPoint(address[0], 60000)); //第三步,监听 serverSocket.Listen(10); //第四步,接受 Socket clientSocket = serverSocket.Accept(); //第五步,接受数据 Byte[] buffer = new Byte[256]; clientSocket.Receive(buffer); if (buffer.Length != 0) this.listBox1.Items.Add(Encoding.UTF8.GetString(buffer)); //第六步,关闭 clientSocket.Shutdown(SocketShutdown.Both); clientSocket.Close(); } private void button5_Click(object sender, EventArgs e) { Socket clientSocket = new Socket(AdddressFamily.InterNetWork,SocketType.Stream,ProtocolType,Tep); IPAddress[]address = Dns.GetHostAddresses(Dns.GetHostAddresses); clientSocket.Connect(AddressFamily[1],53333); string strMsg = this.richTextBox1.Text; Byte[]buffer = Encoding.UTF8.GetBytes(strMsg); if (clientSocket !=null) { clientSocket.Send(buffer); } else MessageBox.Show("something you forgetted"); clientSocket.Shutdown(SocketShutdown.Both); } } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MelanceXin

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值