Files
JJBB/Assets/Project/Script/GameLogic/NetWork/SocketAPI/SocketAPI.cs

138 lines
3.9 KiB
C#
Raw Normal View History

2024-08-23 15:49:34 +08:00
/********************************************************************************
* SocketAPI.cs
* \NetWork\SocketAPI\SocketAPI.cs
*
* 2013-11-29
*
* SocketAPI类
*
* 2014.02.14 ClientSocket.Disconnect(false);
*********************************************************************************/
using System.Net.Sockets;
using System;
using System.Net;
using System.Security;
using Module.Log;
namespace SPacket.Socket_API
{
public class SocketAPI
{
public static Socket Connect(string serverIp, int nPort, ref string result)
{
try
{
IPAddress ipaddr;
if (IPAddress.TryParse(serverIp, out ipaddr))
{
}
else
{
//var ipAddrs = Dns.GetHostAddresses(ServerIP);
var ipAddrs = Dns.GetHostAddresses(serverIp);
if (ipAddrs.Length > 0) ipaddr = ipAddrs[0];
}
LogModule.DebugLog("ipaddr:" + ipaddr);
var socket = new Socket(ipaddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
var tempRemoteIP = new IPEndPoint(ipaddr, nPort);
var epTemp = tempRemoteIP;
socket.Connect(epTemp);
return socket;
}
catch (SocketException e)
{
result = e.ToString();
}
catch (ArgumentOutOfRangeException e)
{
result = e.ToString();
}
catch (ArgumentNullException e)
{
result = e.ToString();
}
catch (ObjectDisposedException e)
{
result = e.ToString();
}
catch (InvalidOperationException e)
{
result = e.ToString();
}
catch (SecurityException e)
{
result = e.ToString();
}
catch (Exception e)
{
result = e.ToString();
}
return null;
}
public static uint Send(Socket client, byte[] buff, uint nLen, SocketFlags flags = SocketFlags.None)
{
try
{
// Byte[] bytesSent = Encoding.ASCII.GetBytes(buff);
return (uint) client.Send(buff, (int) nLen, flags);
}
catch (SocketException e)
{
Console.WriteLine(e.ToString());
//LogModule.ErrorLog(e.ToString());
}
return 0xFFFFFFFF;
}
public static void Close(Socket ClientSocket)
{
try
{
if (ClientSocket.Connected) ClientSocket.Shutdown(SocketShutdown.Both);
}
catch (SocketException e)
{
LogModule.ErrorLog(e.ToString());
}
try
{
ClientSocket.Close();
}
catch (SocketException e)
{
LogModule.ErrorLog(e.ToString());
}
}
public static uint Recv(Socket client, byte[] buff, uint nLen, uint flags = 0)
{
try
{
uint bytes = 0;
bytes = (uint) client.Receive(buff, (int) nLen, (SocketFlags) flags);
// buff += Encoding.ASCII.GetString(bytesReceived, 0, bytes);
return bytes;
}
catch (SocketException e)
{
//Console.WriteLine(e.ToString());
LogModule.ErrorLog(e.ToString());
}
return 0xFFFFFFFF;
}
public static uint available(Socket client)
{
return (uint) client.Available;
}
}
}