static void Main(string[] args) {
StartListening();
}
private static void StartListening() {
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// The DNS name of the computer
// running the listener is "host.contoso.com".
//IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = IPAddress.Parse("192.168.254.142");
IPEndPoint localEndPoint0 = new IPEndPoint(ipAddress, 10000);
IPEndPoint localEndPoint1 = new IPEndPoint(ipAddress, 10001);
IPEndPoint localEndPoint2 = new IPEndPoint(ipAddress, 10002);
IPEndPoint localEndPoint3 = new IPEndPoint(ipAddress, 10003);
IPEndPoint localEndPoint4 = new IPEndPoint(ipAddress, 10004);
IPEndPoint localEndPoint5 = new IPEndPoint(ipAddress, 10005);
IPEndPoint localEndPoint6 = new IPEndPoint(ipAddress, 10006);
IPEndPoint localEndPoint7 = new IPEndPoint(ipAddress, 10007);
IPEndPoint localEndPoint8 = new IPEndPoint(ipAddress, 10008);
IPEndPoint localEndPoint9 = new IPEndPoint(ipAddress, 10009);
// Create a TCP/IP socket.
Socket listener0 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Socket listener1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Socket listener2 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Socket listener3 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Socket listener4 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Socket listener5 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Socket listener6 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Socket listener7 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Socket listener8 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Socket listener9 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and listen for incoming connections.
try {
listener0.Bind(localEndPoint0);
listener1.Bind(localEndPoint1);
listener2.Bind(localEndPoint2);
listener3.Bind(localEndPoint3);
listener4.Bind(localEndPoint4);
listener5.Bind(localEndPoint5);
listener6.Bind(localEndPoint6);
listener7.Bind(localEndPoint7);
listener8.Bind(localEndPoint8);
listener9.Bind(localEndPoint9);
listener0.Listen(0);
listener1.Listen(0);
listener2.Listen(0);
listener3.Listen(0);
listener4.Listen(0);
listener5.Listen(0);
listener6.Listen(0);
listener7.Listen(0);
listener8.Listen(0);
listener9.Listen(0);
while (true) {
// Set the event to nonsignaled state.
allDone.Reset();
// Start an asynchronous socket to listen for connections.
Console.WriteLine("Waiting for a connection");
Log.WriteLogs("Mlog", "Open", "Waiting for a connection");
//Thread thread = new Thread(new ParameterizedThreadStart(ThreadAccept));
//thread.IsBackground = true;
//thread.Start(listener0);
//Thread thread1 = new Thread(new ParameterizedThreadStart(ThreadAccept));
//thread1.IsBackground = true;
//thread1.Start(listener1);
listener0.BeginAccept(new AsyncCallback(AcceptCallback), listener0);
listener1.BeginAccept(new AsyncCallback(AcceptCallback), listener1);
listener2.BeginAccept(new AsyncCallback(AcceptCallback), listener2);
listener3.BeginAccept(new AsyncCallback(AcceptCallback), listener3);
listener4.BeginAccept(new AsyncCallback(AcceptCallback), listener4);
listener5.BeginAccept(new AsyncCallback(AcceptCallback), listener5);
listener6.BeginAccept(new AsyncCallback(AcceptCallback), listener6);
listener7.BeginAccept(new AsyncCallback(AcceptCallback), listener7);
listener8.BeginAccept(new AsyncCallback(AcceptCallback), listener8);
listener9.BeginAccept(new AsyncCallback(AcceptCallback), listener9);
// Wait until a connection is made before continuing.
allDone.WaitOne();
}
} catch (Exception e) {
Console.WriteLine(e.ToString());
Log.WriteLogs("Mlog", "Error", e.ToString());
}
Console.WriteLine("\nPress ENTER to continue");
Console.Read();
}
public static void AcceptCallback(IAsyncResult ar) {
// Signal the main thread to continue.
allDone.Set();
// Get the socket that handles the client request.
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
Console.WriteLine(listener.LocalEndPoint + " connection success");
Log.WriteLogs("Mlog", "Connect", listener.LocalEndPoint + " connection success");
// Create the state object.
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
}
public static void ReadCallback(IAsyncResult ar) {
String content = String.Empty;
// Retrieve the state object and the handler socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
// Read data from the client socket.
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0) {
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
// Check for end-of-file tag. If it is not there, read
// more data.
content = state.sb.ToString();
if (content.Length > 0) {
// All the data has been read from the
// client. Display it on the console.
//Console.WriteLine(handler.LocalEndPoint + "Read {0} bytes from socket. \n Data : {1}", content.Length, content);
Console.WriteLine(handler.LocalEndPoint + " Data : {1}", content.Length, content);
Log.WriteLogs("Mlog", "Data", handler.LocalEndPoint + " Data : " + content);
state.sb.Clear();
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
//Send(handler, content);
} else {
// Not all data received. Get more.
state.sb.Clear();
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
}
} else {
Console.WriteLine("客户端关闭");
Log.WriteLogs("Mlog", "Close", "客户端关闭");
//handler.Close();
}
//读取完成之后, 继续读取... --->如果关闭之后,会一直循环此方法,进入死循环,cpu暴增
// state.sb.Clear();
// handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
}
public class StateObject {
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 1024;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
/// <summary>
/// 写日志 (如果文件打开 还能继续写入)
/// </summary>
/// <param name="fileName">文件名</param>
/// <param name="type">类型</param>
/// <param name="content">内容</param>
public static void WriteLogs(string fileName, string type, string content) {
string path = AppDomain.CurrentDomain.BaseDirectory;
if (!string.IsNullOrEmpty(path)) {
path = AppDomain.CurrentDomain.BaseDirectory + fileName;
if (!Directory.Exists(path)) {
Directory.CreateDirectory(path);
}
path = path + "\\" + DateTime.Now.ToString("yyyyMMdd");
if (!Directory.Exists(path)) {
Directory.CreateDirectory(path);
}
path = path + "\\" + DateTime.Now.ToString("HH") + ".txt";
if (!File.Exists(path)) {
FileStream fs = File.Create(path);
fs.Close();
}
if (File.Exists(path)) {
//这样的情况,不单要与只读方式打开txt文件,而且,需要共享锁。还必须要选择flieShare方式为ReadWrite。因为随时有其他程序对其进行写操作。
FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
StreamWriter sr = new StreamWriter(fs);
sr.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " >>> " + type + " >>> " + content);
sr.Close();
fs.Close();
}
}
}
C# Socket 服务器接收数据 并保存文件(多个端口)
最新推荐文章于 2022-05-24 14:44:05 发布