Comments (4)
can you show your code?
from godsharp.socket.
Client Code
class Program
{
static void Main()
{
int clientCount = 600;
Console.WriteLine("Enter a key to start ");
Console.Read();
for (int i = 0; i < clientCount; ++i)
{
new Thread(
() =>
{
SocketClient client = new SocketClient("127.0.0.1", 7788);
client.OnData = (sender, data) =>
{
//get server data
string message = client.Encoding.GetString(data, 0, data.Length);
Console.SetCursorPosition(0, 0);
Console.WriteLine($"client received data from {sender.RemoteEndPoint.ToString()}: {message}");
};
try
{
client.Connect();
client.Start();
AddSocket(client);
}
catch (Exception ex)
{
Console.WriteLine($"{ex}");
}
})
{ IsBackground = true }.Start();
}
string msg = Console.ReadLine();
while (msg.ToLower() != "q")
{
msg = Console.ReadLine();
if (msg == "go")
{
int num1 = _socketCollection.Count;// new Random().Next(1, clientCount);
Console.WriteLine($"Random num {num1} ..... ");
List<string> ids = new List<string>();
for (int i = 0; i < num1; ++i)
{
int num = new Random().Next(0, _socketCollection.Count);
new Thread(
() =>
{
Thread.Sleep(new Random().Next(1000));
string input = $"[{num}] {GenerateRandomString(new Random().Next(50))}";
_socketCollection[num].Sender.Send(input);
})
{ IsBackground = true }.Start();
}
}
}
Console.WriteLine("end ...");
Console.ReadLine();
}
private const string CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
/// <summary>
/// Generates a random string.
/// </summary>
/// <param name="count">Length of the string.</param>
/// <returns>Generated string</returns>
public static string GenerateRandomString(int count = 8)
{
var random = new Random();
return new string(
Enumerable.Repeat(CHARACTERS, count)
.Select(s => s[random.Next(s.Length)])
.ToArray());
}
}
from godsharp.socket.
Service Code :
class Program
{
///
public class SenderData
{
public TcpSender Sender { get; set; } = null;
public string Data { get; set; } = string.Empty;
}
static ConcurrentDictionary<string, SenderData> _clientCollection = new ConcurrentDictionary<string, SenderData>();
static string OutputLogPath =
System.IO.Path.Combine(
new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName,
"Log");
static void Main()
{
string logPath = System.IO.Path.Combine(
new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName, $"log_{DateTime.Now.ToString("HH_mm_ss")}.txt"
);
FileStream stream = new FileStream(logPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);
StreamWriter writer = new StreamWriter(stream);
if (!Directory.Exists(OutputLogPath))
{
try
{
Directory.CreateDirectory(OutputLogPath);
}
catch (Exception ex)
{
Console.WriteLine($"{ex}");
}
}
Random random = new Random();
SocketServer server = new SocketServer()
{
OnConnected = async (sender) =>
{
Events.OnSocketConnectedEvent.Instance.Publish(sender);
},
OnClosed = (tcpSender) =>
{
Events.OnSocketDisconnectedEvent.Instance.Publish(tcpSender);
}
};
server.OnData = async (sender, data) =>
{
string message = server.Encoding.GetString(data, 0, data.Length);
Events.OnSocketReceiveDataEvent.Instance.Publish(new Events.ReceivePacket() { Message = message, Sender = sender });
};
Events.OnSocketConnectedEvent.Instance.Subscribe(OnConnected
, Prism.Events.ThreadOption.BackgroundThread
);
Events.OnSocketDisconnectedEvent.Instance.Subscribe(OnDisconnected
,Prism.Events.ThreadOption.BackgroundThread
);
Events.OnSocketReceiveDataEvent.Instance.Subscribe(OnDataReceived);
server.Listen();
server.Start();
Console.ReadKey();
writer.Close();
stream.Close();
}
static object _lockObj = new object();
static void OnConnected(TcpSender sender)
{
string key = sender.RemoteEndPoint.ToString();
ThreadPool.QueueUserWorkItem(new WaitCallback(
o =>
{
string p = o as string;
if (p == null)
return;
if (_clientCollection.ContainsKey(p))
_clientCollection[p] = new SenderData() { Data = string.Empty };
else
_clientCollection.TryAdd(p, new SenderData() { Data = string.Empty });
Console.WriteLine($"Count : {_clientCollection.Count}");
}
), key);
}
static void OnDisconnected(TcpSender sender)
{
string key = sender.RemoteEndPoint.ToString();
ThreadPool.QueueUserWorkItem(new WaitCallback(
o =>
{
string p = o as string;
if (p == null)
return;
if (_clientCollection.ContainsKey(p))
{
SenderData data = null;
_clientCollection.TryRemove(p, out data);
}
Console.WriteLine($"Client {p} is disconnected, totalCount : {_clientCollection.Count}");
}
), key);
}
static void OnDataReceived (Events.ReceivePacket packet)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(
o =>
{
Events.ReceivePacket p = o as Events.ReceivePacket;
if (p == null)
return;
Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] {p.Sender.RemoteEndPoint}::{p.Message}");
}), packet);
}
}
from godsharp.socket.
My way to duplicate : I run the server.exe. Later, I run client.exe to create 600 sockets to the server and close the client.exe [several times]. The server will meet the OutOfIndex Exception.
from godsharp.socket.
Related Issues (16)
- how to gracefully stop the socket server? HOT 1
- I recive clone message after disconnect and reconnect HOT 7
- How to receive all bytes in the OnReceived event? HOT 4
- udp服务器怎么用? HOT 1
- [Request] TLS support HOT 1
- The lastversion cause the not supported error HOT 4
- TCP client 调用STOP 服务端显示没有完全断开问题
- tcp调用同步接收方法 Receive(),对方发送的第一条数据接收不到,第二条数据才能接收到
- onclose for client disconnected HOT 1
- how can the server send message to client ? HOT 2
- what will happened if a client end it's connection and reconnect HOT 9
- promising project but has no tests. HOT 1
- TCP Sample crash when the client connect to a non-open server HOT 2
- Problem with Client? HOT 1
- message gets cut. when more then 32k bytes sent HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from godsharp.socket.