C# Socket编程

服务端(server side)

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

namespace MyChatServer
{
   
    internal class server
    {
        [STAThread]
        private static void Main(string[] args)
        {
            int recv;
            byte[] data = new byte[1024];
            IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 9050);
            Socket newSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            newSocket.Bind(ipEnd);
            newSocket.Listen(10);
            Console.WriteLine("Waiting for a client...");
            Socket client = newSocket.Accept();
            IPEndPoint clientIp = client.RemoteEndPoint as IPEndPoint;
            Console.WriteLine("connect with client: " + clientIp.Address + " at port; " + clientIp.Port);

            string welcome = "welcome here";
            data = Encoding.ASCII.GetBytes(welcome);
            client.Send(data, data.Length, SocketFlags.None);

            while (true)
            {
                data = new byte[1024];
                recv = client.Receive(data);
                Console.WriteLine("recv = " + recv);

                if (recv == 0)
                {
                    break;
                }
                
                Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
                client.Send(data, recv, SocketFlags.None);
            }

            Console.WriteLine("Disconnected from " + clientIp.Address);
            client.Close();
            newSocket.Close();
        }
    }
}

客户端(Client Side)

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace tcpclient
{
    /// <summary>
    /// Class1 的摘要说明。
    /// </summary>
    class client
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            //
            // TODO: 在此处添加代码以启动应用程序
            //
            byte[] data=new byte[1024];
            Socket newclient=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
            Console.Write("please input the server ip:");
            string ipadd=Console.ReadLine();
            Console.WriteLine();
            Console.Write("please input the server port:");
            int port=Convert.ToInt32(Console.ReadLine());
            IPEndPoint ie=new IPEndPoint(IPAddress.Parse(ipadd),port);//服务器的IP和端口
            try
            {
                //因为客户端只是用来向特定的服务器发送信息,所以不需要绑定本机的IP和端口。不需要监听。
                newclient.Connect(ie);
            }
            catch(SocketException e)
            {
                Console.WriteLine("unable to connect to server");
                Console.WriteLine(e.ToString());
                return;
            }
            int recv = newclient.Receive(data);
            string stringdata=Encoding.ASCII.GetString(data,0,recv);
            Console.WriteLine(stringdata);
            while(true)
            {
                string input=Console.ReadLine();
                if(input=="exit")
                    break;
                newclient.Send(Encoding.ASCII.GetBytes(input));
                data=new byte[1024];
                recv=newclient.Receive(data);
                stringdata=Encoding.ASCII.GetString(data,0,recv);
                Console.WriteLine(stringdata);
            }
            Console.WriteLine("disconnect from sercer");
            newclient.Shutdown(SocketShutdown.Both);
            newclient.Close();

        }
    }
}

如果要在Unity中在web platform使用Socket编程(Window平台),需要做以下操作:

1、首先找到sockpol.exe文件。文件路径..\Unity\Editor\Data\Tools\SocketPolicyServer\sockpol.exe

2、然后打开cmd控制台,并且进入到sockpol.exe目录,打开sockpol服务,服务不能关闭。在cmd中使用netstat -ano命令可以看到一个843端口的服务。


3、在客户端连接(Unity中)的开始部分,加上下面这句代码。

Security.PrefetchSocketPolicy(ipAddress, 843); //端口号843固定,ipAddress为服务器的ip



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值