Unity Socket

来源:互联网 发布:中国文化深层结构 知乎 编辑:程序博客网 时间:2024/04/29 11:51
服务器 端
<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
原创粉丝点击