Socket初试

服务器

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

namespace SocketServer
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建Socket
            Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress ipaddress = IPAddress.Parse("192.168.0.99");
            IPEndPoint endpoint = new IPEndPoint(ipaddress, 50000);
            tcpServer.Bind(endpoint);
            tcpServer.Listen(100);
            Console.WriteLine("服务器启动完成");
          
            //收到客户端Socket
            Socket clientSocket = tcpServer.Accept();
            Console.WriteLine("接收到客户端的链接请求");

            //向客户端发送消息
            string message = "Hello Client";
            var data = Encoding.UTF8.GetBytes(message);
            clientSocket.Send(data);
            Console.WriteLine("服务器向客户端发送了一条消息" + message);

            //收到客户端消息
            byte[] data2 = new byte[1024];
            int length = clientSocket.Receive(data2);
            string message2 = Encoding.UTF8.GetString(data2, 0, length);
            Console.WriteLine("收到服务器发送消息" + message2);
            //clientSocket.Close();
            //tcpServer.Close();
            //Console.Read();
        }
    }
}

客户端

Socket封装

using System;
using System.Net;
using System.Net.Sockets;
using System.Security;

public class SocketClient
{
	public static Socket Connect( string ServerIP, int nPort, ref string result )
	{
		try
		{
			Socket socket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
			IPEndPoint iPEndPoint = new IPEndPoint( IPAddress.Parse( ServerIP ), nPort );
			EndPoint remoteEP = iPEndPoint;
			socket.Connect( remoteEP );
			return socket;
		}
		catch( SocketException ex )
		{
			result = ex.ToString();
		}
		catch( ArgumentOutOfRangeException ex2 )
		{
			result = ex2.ToString();
		}
		catch( ArgumentNullException ex3 )
		{
			result = ex3.ToString();
		}
		catch( ObjectDisposedException ex4 )
		{
			result = ex4.ToString();
		}
		catch( InvalidOperationException ex5 )
		{
			result = ex5.ToString();
		}
		catch( SecurityException ex6 )
		{
			result = ex6.ToString();
		}
		catch( Exception ex7 )
		{
			result = ex7.ToString();
		}
		return null;
	}

	public static uint Send( Socket client, byte[] buff, uint nLen, SocketFlags flags = SocketFlags.None )
	{
		try
		{
			return (uint)client.Send( buff, (int)nLen, flags );
		}
		catch( SocketException ex )
		{
	//				Console.WriteLine( ex.ToString() );
		}
		return 4294967295u;
	}

	public static void Close( Socket clientSocket )
	{
		try
		{
			if( clientSocket.Connected )
			{
				clientSocket.Shutdown( SocketShutdown.Both );
			}
		}
		catch( SocketException ex )
		{
	//				Console.WriteLine( ex.ToString() );
		}
		try
		{
			clientSocket.Close();
		}
		catch( SocketException ex2 )
		{
	//				Console.WriteLine( ex2.ToString() );
		}
	}

	public static uint Recv( Socket client, byte[] buff, uint nLen, uint flags = 0u )
	{
		try
		{
	//				return (uint)client.Receive( buff, (int)nLen, (SocketFlags)flags );
			return (uint)client.Receive( buff );
		}
		catch( SocketException ex )
		{
	//				Console.WriteLine( ex.ToString() );
		}
		return 4294967295u;
	}

	public static uint available( Socket socket )
	{
		return (uint)socket.Available;
	}
}

Socket测试

using UnityEngine;
using System.Collections;
using System.Net;
using System.Net.Sockets;

public class SocketTest : MonoBehaviour 
{
	private string m_host = "192.168.0.99";

	private int m_port = 50000;

	private Socket m_client = null;

	private byte[] m_BufferTemp = new byte[1024];

	private uint receLength = 0u;

	void Start()
	{
		string empty = string.Empty;
		m_client = SocketClient.Connect( this.m_host, this.m_port, ref empty );
		if( m_client != null )
		{
			string sendMessage = "Client send message help" + Time.realtimeSinceStartup;
			m_client.Send( System.Text.Encoding.ASCII.GetBytes(sendMessage) );
		}
		if( m_client != null )
		{
			receLength = SocketClient.Recv( this.m_client, this.m_BufferTemp, 1024u, 0u );
			if( receLength != 0u && receLength != 4294967295u )
			{
				string str = System.Text.Encoding.UTF8.GetString( this.m_BufferTemp );
				Debug.Log( "get from server " + str + receLength + " bytes" );
				receLength = 0u;
			}
		}
	}
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值