hi i work on a small project which includes socketcommunication.
Specifically a TLS connection to a server.
The Serverside works so far. But the client seems to block all parallelism tasks.
Does anybody know where to get a sample with Sockets using multiple ports at the client side?
Could it be the problem that TCPClient only supports one port on the clientside?
This code should be the backend of a simple application.
As you can see i also tried to Queue the data. Simply ignore it.
here comes my client code:
public class IMClient
{
public IMClient(string ip, int port)
{
Server = ip;
Port = port;
}
Task tcpThread;
bool _conn = false;
private string Server = "";
private int Port;
internal MultithreadedQueue<IDWrapper> CommandInput { get => commandInput; set => commandInput = value; }
internal MultithreadedQueue<IDWrapper> CommandResult { get => commandResult; set => commandResult = value; }
private MultithreadedQueue<IDWrapper> commandInput = new MultithreadedQueue<IDWrapper>(100);
private MultithreadedQueue<IDWrapper> commandResult = new MultithreadedQueue<IDWrapper>(100);
TcpClient client;
NetworkStream netStream;
SslStream ssl;
BinaryReader br;
BinaryWriter bw;
Stream input;
Stream output;
string s;
public void connect()
{
_conn = true;
tcpThread = Task.Run(SetupConn);
}
public void Disconnect()
{
if (_conn)
CloseConn();
}
private async Task<Task<object>> SetupConn()
{
bool retry = false;
do {
try
{
client = new TcpClient(Server, Port);
client.NoDelay = true;
client.SendBufferSize = 1024;
client.ReceiveBufferSize = 4096;
netStream = client.GetStream();
ssl = new SslStream(netStream, false, new RemoteCertificateValidationCallback(ValidateCert));
ssl.AuthenticateAsClient("InstantMessengerServer");
br = new BinaryReader(ssl, Encoding.UTF8);
bw = new BinaryWriter(ssl, Encoding.UTF8);
retry = false;
}
catch (Exception e)
{
retry = true;
}
} while (retry);
IDWrapper idw = commandInput.Dequeue();
string content = idw.Content;
string id = idw.ID;
SendCallback(ref content, ref id);
CloseConn();
return Task.FromResult<object>(null);
}
public async Task<string> SendCallbackUnbuffered(string action, int recivebuffersize = 4096)
{
string res = "";
try
{
byte[] a = StringToByteArray(action);
if(!_conn)
{
connect();
}
while (bw == null);
ssl.WriteAsync(a, 0, a.Length);
byte[] r = new byte[recivebuffersize];
ssl.ReadAsync(r, 0, recivebuffersize);
CloseConn();
}
catch (IOException e)
{
Console.WriteLine(e.Message);
}
return res;
}
What I have tried:
I tried several things which should make the SendCallback Method awaitable.
But it does not work.
Can anyone provide me a example of a nonblocking socketcommunication in c#, or at least a hint how to do it?