/// TCP [C# http://www.showjim.com/]
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
using System.IO;
using sys.collections.generic;
namespace sys.net
{
///
/// TCP
///
public class tcpListener
{
///
///
///
/// Socket
/// ( )
public delegate bool listerHandle(int threadId);
///
/// TCP
///
private TcpListener listener = null;
///
///
///
private bool isStart = false;
///
///
///
private byte[] startSend;
///
/// Socket
///
private Dictionary sockets; //Socket.RemoteEndPoint.ToString(); IP , 127.0.0.1:80
///
///
///
private listerHandle listenSocket;
#region TCP
///
/// TCP
///
///
///
///
public tcpListener(int port, listerHandle ListenSocket, byte startSendByte)
{
if (port > 0 && port < 65536 && ListenSocket != null)
{
try
{
listener = new TcpListener(IPAddress.Any, port); //IPAddress.Parse("127.0.0.1")
listener.Start();
startSend = new byte[] { startSendByte };
listenSocket = ListenSocket;
sockets = new Dictionary();
isStart = true;
Thread socketThread = new Thread(getSockets);
socketThread.Start();
}
catch (System.Security.SecurityException) { } //
catch (Exception error)
{// , Stop 、
close();
sys.exception.debug.throwException(System.Reflection.MethodBase.GetCurrentMethod(), " " + port.ToString() + @"TCP )
" + error.ToString());
}
}
}
#endregion
#region TCP
///
/// TCP
///
~tcpListener() { close(); }
///
/// TCP
///
public void close()
{
isStart = false;
listenSocket = null;
if (sockets != null)
{
foreach (int threadId in sockets.Keys)
{
try { sockets[threadId].Close(); }
catch { }
}
sockets = null;
}
if (listener != null) { listener.Stop(); listener = null; }
}
#endregion
#region
///
///
///
private void getSockets()
{
while (isStart && listener != null)
{
Socket socket = null;
Thread socketThread = null;
try
{
socket = listener.AcceptSocket();
if (startSend != null) socket.Send(startSend);
int key = sys.pub.identity;
sockets.Add(key, socket);
(socketThread = new Thread(new ParameterizedThreadStart(listen))).Start(key);
socketThread.IsBackground = true;
}
catch
{
if (socket != null) { socket.Close(); socket = null; }
if (socketThread != null && socketThread.IsAlive) { socketThread.Abort(); }
}
}
}
#endregion
#region
///
///
///
///
private void listen(object identity)
{
int key = (int)identity;
Socket socket = sockets.get(key, null);
if (socket != null)
{
try
{
for (bool noQuit = true; isStart && noQuit && socket.Connected; noQuit = listenSocket(key)) ;
}
finally
{
socket.Close();
sockets.remove(key);
}
}
}
#endregion
#region
///
///
///
/// Socket
/// -2 ,-1
public int receiveByte(int threadId)
{
byte[] bytes = new byte[1];
int length = _receive(threadId, bytes, 0, 1);
return length == 1 ? (int)bytes[0] : (length == 0 ? -1 : -2);
}
///
/// 15
///
/// Socket
/// -2 ,-1
public int receiveInt15(int threadId)
{
byte[] bytes = new byte[2];
int value = _receive(threadId, bytes, 0, 2);
if (value == 2)
{
if ((value = BitConverter.ToInt16(bytes, 0)) < 0) value = 0;
}
else value = (value < 0 ? -2 : -1);
return value;
}
///
/// 31
///
/// Socket
/// -2 ,-1
public int receiveInt31(int threadId)
{
byte[] bytes = new byte[4];
int value = _receive(threadId, bytes, 0, 4);
if (value == 4)
{
if ((value = BitConverter.ToInt32(bytes, 0)) < 0) value = 0;
}
else value = (value < 0 ? -2 : -1);
return value;
}
/// 63
///
/// Socket
/// -2 ,-1
public long receiveInt63(int threadId)
{
byte[] bytes = new byte[8];
long value = -2;
int length = _receive(threadId, bytes, 0, 8);
if (length == 8)
{
if ((value = BitConverter.ToInt64(bytes, 0)) < 0) value = 0;
}
else value = (length < 0 ? -2 : -1);
return value;
}
///
///
///
/// Socket
///
/// , -1
public int receive(int threadId, byte[] bytes)
{
return isStart && bytes != null && bytes.Length > 0 ? _receive(threadId, bytes, 0, bytes.Length) : -1;
}
///
///
///
/// Socket
///
///
/// , -1
public int receive(int threadId, byte[] bytes, int startIndex)
{
return isStart && bytes != null && bytes.Length > startIndex ? _receive(threadId, bytes, startIndex, bytes.Length - startIndex) : -1;
}
///
///
///
/// Socket
///
///
///
/// , -1
public int receive(int threadId, byte[] bytes, int startIndex, int length)
{
return isStart && bytes != null && startIndex >= 0 && length > 0 && bytes.Length >= startIndex + length ? _receive(threadId, bytes, startIndex, length) : -1;
}
///
///
///
/// Socket
///
///
public byte[] receiveBytes(int threadId, int length)
{
byte[] bytes = null;
if (length > 0 && length != _receive(threadId, bytes = new byte[length], 0, length)) bytes = null;
return bytes;
}
///
///
///
/// Socket
///
///
///
/// , -1
private int _receive(int threadId, byte[] bytes, int startIndex, int length)
{
int receiveLength = -1;
Socket socket = sockets.get(threadId, null);
if (socket != null)
{
try
{
for (int nextLength = length; nextLength != 0; nextLength -= receiveLength) startIndex += (receiveLength = socket.Receive(bytes, startIndex, nextLength, SocketFlags.None));
receiveLength = length;
}
catch
{
receiveLength = -1;
socket.Close();
}
}
return receiveLength;
}
///
///
///
/// Socket
///
///
///
/// , -1
private int _receive(Socket socket, byte[] bytes, int startIndex, int length)
{
int receiveLength = -1;
try
{
for (int nextLength = length; nextLength != 0; nextLength -= receiveLength) startIndex += (receiveLength = socket.Receive(bytes, startIndex, nextLength, SocketFlags.None));
receiveLength = length;
}
catch
{
receiveLength = -1;
socket.Close();
}
return receiveLength;
}
#endregion
#region
///
///
///
/// Socket
///
///
public bool send(int threadId, byte[] bytes)
{
return isStart && bytes != null && bytes.Length > 0 && _send(threadId, bytes);
}
///
///
///
/// Socket
///
///
///
public bool send(int threadId, byte[] bytes, int startIndex)
{
return isStart && bytes != null && startIndex >= 0 && bytes.Length > startIndex && _send(threadId, bytes, startIndex, bytes.Length - startIndex);
}
///
///
///
/// Socket
///
///
///
///
public bool send(int threadId, byte[] bytes, int startIndex, int length)
{
return isStart && bytes != null && startIndex >= 0 && length >= 0 && bytes.Length >= startIndex + length && _send(threadId, bytes, startIndex, length);
}
///
///
///
/// Socket
///
///
public bool send(int threadId, string sendString)
{
return isStart && sendString != null && sendString.Length != 0 && _send(threadId, Encoding.Default.GetBytes(sendString));
}
///
///
///
/// Socket
///
///
///
public bool send(int threadId, string sendString, Encoding code)
{
return isStart && sendString != null && sendString.Length != 0 && code != null && _send(threadId, code.GetBytes(sendString));
}
///
///
///
/// Socket
///
///
private bool _send(int threadId, byte[] bytes)
{
bool isSend = false;
Socket socket = sockets.get(threadId, null);
if (socket != null)
{
try
{
socket.Send(bytes, SocketFlags.None);
isSend = true;
}
catch { socket.Close(); }
}
return isSend;
}
///
///
///
/// Socket
///
///
///
///
private bool _send(int threadId, byte[] bytes, int startIndex, int length)
{
bool isSend = false;
Socket socket = sockets.get(threadId, null);
if (socket != null)
{
try
{
socket.Send(bytes, startIndex, length, SocketFlags.None);
isSend = true;
}
catch { socket.Close(); }
}
return isSend;
}
#endregion
#region
///
///
///
/// Socket
///
///
///
public bool saveFile(int threadId, string fileName, long length)
{
bool isSave = false;
if (isStart && fileName != null && fileName.Length != 0 && length > 0 && sockets.ContainsKey(threadId))
{
FileStream fileStream = null;
try { fileStream = new FileStream(fileName, FileMode.CreateNew, FileAccess.Write, FileShare.None, pub.streamBufferLength); }
catch { }
if (fileStream != null)
{
isSave = saveFile(threadId, fileStream, 0, length, pub.streamBufferLength);
fileStream.Close();
if (!isSave) File.Delete(fileName);
}
}
return isSave;
}
///
///
///
/// Socket
///
///
///
///
public bool saveFile(int threadId, FileStream fileStream, long startIndex, long length)
{
return saveFile(threadId, fileStream, startIndex, length, pub.streamBufferLength);
}
///
///
///
/// Socket
///
///
///
///
///
public bool saveFile(int threadId, FileStream fileStream, long startIndex, long length, int bufferLength)
{
bool isSave = false;
if (isStart && fileStream != null && startIndex >= 0 && length > 0 && bufferLength > 0)
{
long endIndex = startIndex + length;
if (endIndex > 0)
{
try
{
fileStream.SetLength(endIndex);
fileStream.Seek(startIndex, SeekOrigin.Begin);
}
catch { }
int readLength;
byte[] bytes = new byte[bufferLength];
isSave = true;
try
{
while (isSave && length >= bufferLength)
{
if (isSave = ((readLength = receive(threadId, bytes)) == bufferLength))
{
fileStream.Write(bytes, 0, readLength);
length -= readLength;
}
}
if (isSave && length != 0 && (isSave = (receive(threadId, bytes, 0, readLength = (int)length) == readLength))) fileStream.Write(bytes, 0, readLength);
}
catch { isSave = false; }
}
}
return isSave;
}
#endregion
#region
///
///
///
private const int examplePort = 9999;
///
///
///
private static byte exampleStartSendByte = 200;
///
/// TCP
///
private static sys.net.tcpListener exampleListener = new sys.net.tcpListener(examplePort, exampleHandle, exampleStartSendByte);
///
///
///
/// Socket
/// ( )
private static bool exampleHandle(int key)
{
#region
int byteValue = exampleListener.receiveByte(key); //
int int31Value = exampleListener.receiveInt31(key); // 31
byte[] bytes=new byte[int31Value];
int length = exampleListener.receive(key, bytes, 0, int31Value); //
#endregion
#region
bool isSend = exampleListener.send(key, bytes, 0, bytes.Length); //
#endregion
return false;
}
#endregion
}
}