ソケット通信の一般的な方法
19153 ワード
tcp ,
/// <summary>
/// tcp
/// </summary>
/// <param name="ip"> ip</param>
/// <param name="port"> </param>
/// <returns></returns>
public static Socket ConnectServer(string ip, int port)
{
Socket s = null;
try
{
IPAddress ipAddress = IPAddress.Parse(ip);
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, port);
s = new Socket(ipEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
s.Connect(ipEndPoint);
if (s.Connected == false) s = null;
}
catch (Exception)
{
}
return s;
}
送信データ: /// <summary>
///
/// </summary>
/// <param name="socket"> socket</param>
/// <param name="buffer"> </param>
/// <param name="outTime"> , ( -1 , )</param>
/// <returns>0: ;-1: ;-2: ;-3: </returns>
public static int SendData(Socket socket, byte[] buffer, int outTime)
{
if (socket == null || socket.Connected == false)
{
throw new ArgumentException(" socket null, ");
}
if (buffer == null || buffer.Length == 0)
{
throw new ArgumentException(" buffer null , 0");
}
int flag = 0;
try
{
int left = buffer.Length;
int sndLen = 0;
int hasSend = 0;
while (true)
{
if ((socket.Poll(outTime * 1000, SelectMode.SelectWrite) == true))
{
//
sndLen = socket.Send(buffer, hasSend, left, SocketFlags.None);
left -= sndLen;
hasSend += sndLen;
//
if (left == 0)
{
flag = 0;
break;
}
else
{
//
if (sndLen > 0)
{
continue;
}
else //
{
flag = -2;
break;
}
}
}
else //
{
flag = -1;
break;
}
}
}
catch (SocketException)
{
//Log
flag = -3;
}
return flag;
}
stringデータを送ります.方法System.Text.Enccoding.Default.GetByttesで上記の方法をカプセル化します. /// <summary>
///
/// </summary>
/// <param name="socket"> socket</param>
/// <param name="buffer"> </param>
/// <param name="outTime"> , ( -1 , )</param>
/// <returns>0: ;-1: ;-2: ;-3: </returns>
public static int SendData(Socket socket, string buffer, int outTime)
{
if (buffer == null || buffer.Length == 0)
{
throw new ArgumentException("buffer null 0.");
}
return SendData(socket, System.Text.Encoding.Default.GetBytes(buffer), outTime);
}
受信データ: /// <summary>
///
/// </summary>
/// <param name="socket"> </param>
/// <param name="buffer"> ( , buffer )</param>
/// <param name="outTime"> , ( -1 , )</param>
/// <returns></returns>
public static int RecvData(Socket socket, byte[] buffer, int outTime)
{
if (socket == null || socket.Connected == false)
{
throw new ArgumentException("socket null, ");
}
if (buffer == null || buffer.Length == 0)
{
throw new ArgumentException("buffer null , 0");
}
buffer.Initialize();
int left = buffer.Length;
int curRcv = 0;
int hasRecv=0;
int flag = 0;
try
{
while (true)
{
if (socket.Poll(outTime * 1000, SelectMode.SelectRead) == true)
{
//
curRcv = socket.Receive(buffer, hasRecv, left, SocketFlags.None);
left -= curRcv;
hasRecv += curRcv;
//
if (left == 0)
{
flag = 0;
break;
}
else
{
//
if (curRcv > 0)
{
continue;
}
else //
{
flag = -2;
break;
}
}
}
else //
{
flag = -1;
break;
}
}
}
catch (SocketException)
{
//Log
flag = -3;
}
return flag;
}
住所:http://blog.csdn.net/love__coder/articale/detail/6649688