C#笔记,socket通信代码

本文详细介绍了使用C#进行Socket通信的步骤和代码实现,包括客户端和服务器端的创建,连接建立,数据传输及断开连接的过程,是C#网络编程的一个基础实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

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

namespace SocketServer
{
    class Program
    {
        static Socket ServerSocket;
        static Socket MyClient;
        static void Main(string[] args)
        {
            IPAddress ip = IPAddress.Parse("127.0.0.1");//服务器端IP地址  
            IPEndPoint iep = new IPEndPoint(ip, 5555);//服务端地址及端口  
                                                      //1.建立套接字,以Tcp协议链接,字节流的方式进行数据传输  
            ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //设置Socket地址可重复使用  
            ServerSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            //2.绑定套接字  
            ServerSocket.Bind(iep);
            //3.监听套接字  
            ServerSocket.Listen(10);
            //4.等待客户端请求  
            MyClient = ServerSocket.Accept();
            //5.向客户端发送消息  
            MyClient.Send(Encoding.Unicode.GetBytes("链接成功"));
            while (true)
            {
                new Thread(receive).Start();
                new Thread(send).Start();
            }

            //关闭套接字的发送与接收  
            MyClient.Shutdown(SocketShutdown.Both);
            //关闭MyClient  
            MyClient.Close();
            //关闭MySocket  
            ServerSocket.Close();


        }
        //接收消息
        public static void receive()
        {
            //定义字节数组  
            byte[] buf = new byte[1024];
            //3.接收来自服务端的信息,并保存在字节数组中  
            int k = MyClient.Receive(buf);
            //输出显示服务端发送的信息  
            Console.WriteLine(Encoding.Unicode.GetString(buf, 0, k));
        }
        //发送消息
        public static void send()
        {
            string sendstr = Console.ReadLine();
            if (sendstr.Length > 0 && !sendstr.Equals(null))
                MyClient.Send(Encoding.Unicode.GetBytes(sendstr));
            else Console.WriteLine("不能发送空字符,请重新输入");
        }
    }
}
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace SocketClient
{
    class Program
    {
        static Socket ClientSocket;
        static void Main(string[] args)
        {
            //所连接服务器端IP地址  
            IPAddress remoteIp = IPAddress.Parse("127.0.0.1");
            //所连接服务端地址及端口  
            IPEndPoint iep = new IPEndPoint(remoteIp, 5555);
            //1.建立套接字,以Tcp协议链接,字节流的方式进行数据传输  
            ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                //2.建立与服务端的链接  
                ClientSocket.Connect(iep);
                //3.向服务端发送信息  
                ClientSocket.Send(Encoding.Unicode.GetBytes("客户已经连接"));
                while (true)
                {
                    new Thread(receive).Start();
                    new Thread(send).Start();
                }                
            }         
            catch (Exception ex)
            {
                Console.WriteLine("Unexpection Exception:{0}", ex.ToString());
            }
            finally
            {
                //4.关闭套接字  
                ClientSocket.Shutdown(SocketShutdown.Both);
                ClientSocket.Close();
            }
        }
        //接收消息
        public static void receive()
        {
            //定义字节数组  
            byte[] buf = new byte[1024];
            //3.接收来自服务端的信息,并保存在字节数组中  
            int k = ClientSocket.Receive(buf);
            //输出显示服务端发送的信息  
            Console.WriteLine(Encoding.Unicode.GetString(buf, 0, k));
        }
        //发送消息
        public static void send()
        {
            string sendstr = Console.ReadLine();
            if (sendstr.Length > 0 && !sendstr.Equals(null))
                ClientSocket.Send(Encoding.Unicode.GetBytes(sendstr));
            else Console.WriteLine("不能发送空字符,请重新输入");
        }


    }
}





                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

搬砖民工金币

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

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

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

打赏作者

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

抵扣说明:

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

余额充值