Unity Socket

服务器 端
<pre name="code" class="csharp">using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;


namespace SocketSever
{
    class Program
    {   static List<Client>clientList =new List<Client>();  //建立连接的数组!!!!
        static void Main(string[] args)
        {
            int port = 6180;               //端口
            string host = "192.168.10.75"; //IP
            //创建终结点
            IPAddress ip = IPAddress.Parse(host);
            IPEndPoint ipe = new IPEndPoint(ip, port);


            //创建Socket并开始监听
            Socket TcpSever = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //创建一个Socket对象,如果用UDP协议,则要用SocketTyype.Dgram类型的套接字
            TcpSever.Bind(ipe);                                                                            //绑定EndPoint对象(6180端口和ip地址)
            TcpSever.Listen(100);            //开始监听 监听数//接受到Client连接,为此连接建立新的Socket,并接受消息
         Console.WriteLine("等待客户端连接。。。。。");
                                             //死循环接受新的连接
            while(true){
            Socket temp = TcpSever.Accept();  //为新建立的连接创建新的Socket
            Console.WriteLine("有一个已经连接过来了!");
            Client client = new Client(temp); //把与客户的通讯交互逻辑做到Client 类里面(收发消息)
            clientList.Add(client);           //新的连接放入集合
            }




            //Console.WriteLine("建立连接");
            //string recvStr = "";
            //byte[] recvBytes = new byte[1024];
            //int bytes;
            //bytes = temp.Receive(recvBytes, recvBytes.Length, 0); //从客户端接受消息
            //recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);


            给Client端返回信息
            //Console.WriteLine("server get message:{0}", recvStr);    //把客户端传来的信息显示出来
            //string sendStr = "ok!Client send message successful!";
            //byte[] bs = Encoding.ASCII.GetBytes(sendStr);
            //temp.Send(bs, bs.Length, 0);                             //返回信息给客户端
            //temp.Close();
            //TcpSever.Close();
            //Console.ReadLine();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace SocketSever
{
    /// <summary>
    /// 与客户端做通讯
    /// </summary>
    class Client
    {
        private Socket clientSocket;
        public Client(Socket s)
        {
            clientSocket = s;
        }
    }
}



                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值