最简单的C#socket通信

本文介绍了一个简单的TCP服务器和客户端的实现过程,包括服务器端的监听设置与客户端的连接及数据交互流程。通过C#代码示例展示了如何创建Socket进行通信。

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

服务器端

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;

namespace SimpleServer
{
    class Program
    {
        static void Main(string[] args)
        {
            // 服务器ip地址
            string ip = "127.0.0.1";
            // 服务器端口
            int port = 8000;

            try
            {
                // 获得终端
                IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(ip), port);
                // 创建Socket
                Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                // 将Socket绑定到终端地址上
                listener.Bind(ipe);
                // 开始监听 最大允许处理1000个连接
                listener.Listen(1000);
                Console.WriteLine("开始监听");
                // 开始接受客户端请求 程序在这里会卡阻住
                Socket mySocket=listener.Accept();

                byte[] bs = new byte[1024];
                int n = mySocket.Receive(bs);
                // 将客户端发来的数据返回给客户端
                mySocket.Send(bs);
                // 半闭与客户端的连接
                mySocket.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

        }
    }
}

客户端

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace SimpleClient
{
    class Program
    {
        static void Main(string[] args)
        {
            // 服务器ip地址
            string ip = "127.0.0.1";
            // 服务器端口
            int port = 8000;
            try
            {
                // 获得终端
                IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(ip), port);
                // 创建Socket
                Socket client = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                // 开始连接服务器,程序在这里会阻住,直接连接成功或失败
                client.Connect(ipe);
                Console.WriteLine("连接到服务器");
                //向服务器发送数据
                string data = "hello,world";
                byte[] bs=UTF8Encoding.UTF8.GetBytes(data);
                client.Send(bs);
                // 接收到服务器的数据
                byte[] rev = new byte[256];
                // 接收到服务器返回的数据
                client.Receive(rev);
                Console.WriteLine(UTF8Encoding.UTF8.GetString(rev));
                // 关闭连接
                client.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
           
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

四夕立羽

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

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

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

打赏作者

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

抵扣说明:

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

余额充值