前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >最简单的C#socket通信

最简单的C#socket通信

作者头像
立羽
发布2023-08-24 13:24:28
1420
发布2023-08-24 13:24:28
举报
文章被收录于专栏:Unity3d程序开发

服务器端

代码语言:javascript
复制
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);
            }

        }
    }
}

客户端

代码语言:javascript
复制
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);
            }
           
        }
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016-04-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档