Socket using. Data is not sending on the second time - c#

Issue description.
I sending and receiving data. When i launch program, data who i send and receive, displayed is right. If relaunch program in 1 minutes, no more, data send and receive displayed is currect.
BUT! IF i relaunching program more then after 2 minutes, FIRST receiving and sending displayed is right, BUT SECOND sending and receiving data, is not displayed (((
What's happening, and how i fix this???
Thanks for any help!
public override bool Connect()
{
try
{
if (NetClient != null)
{
NetClient.Close();
}
NetClient = new Socket(ConnectionPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
IAsyncResult result = NetClient.BeginConnect(ConnectionPoint, null, null);
bool success = result.AsyncWaitHandle.WaitOne(connectionDelay, false/*true*/);
if (NetClient.Connected)
{
Log("report.log", string.Format("Connection OK"));
return true;
}
Log("report.log", string.Format("NetClient is not connected"));
}
catch (Exception e)
{
MessageBox.Show(e.Message);
Log("report.log", string.Format("NetClient error while connecting: {0}", e.Message));
}
return false;
}
public override bool Send(byte[] data)
{
try
{
if (NetClient.Connected)
{
NetClient.SendTo(data, ConnectionPoint);
Thread.Sleep(transferDelay);
return true;
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
return false;
}
public override string Receive(int length)
{
byte[] data = new byte[bufferSize]; // bufferSize = i tryed any buffer from 5 bytes to 16384 bytes
string strbuff = "";
try
{
if (NetClient.Connected)
{
do
{
IAsyncResult result = NetClient.BeginReceive(data, 0, bufferSize, SocketFlags.None, null, null);
bool success = result.AsyncWaitHandle.WaitOne(connectionDelay, true);
int receivedBytesCount = NetClient.EndReceive(result);
if (receivedBytesCount == 0)
{
receivedBytesCount = 0;
}
strbuff += Encoding.ASCII.GetString(data, 0, receivedBytesCount);
} while (NetClient.Available > 0);
if (NetClient != null && NetClient.Connected)
{
NetClient.Shutdown(SocketShutdown.Both);
NetClient.Close();
}
return strbuff;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return null;
}
public override void Disconnect()
{
try
{
if (NetClient.Connected)
{
NetClient.Shutdown(SocketShutdown.Both);
NetClient.Close();
}
else
{
if (NetClient != null)
{
NetClient.Close();
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}

Related

CPU running High after 2 hours of use

I'm working on a c# framework 4.8 project which has a number of tcp sockets (+/-20) waiting for data. When I start the project everything is fine and it receives like 10 packets a minute.
CPU is low round 10%
When the program runs for like 2 hours the CPU rises to 40-50% even when no data is received.
I've attached the remote debugger and discovered the Garbage Collector is collecting like Crazy. After profiling the CPU the Hotpath ends in System.Configuration.Dll.
Can anybody tell me what the system.configuration.dll has to do with sockets and how to fix this?
public class TcpConnectionState: ConnectionStateBase, IConnectionState
{
private byte[] _buffer;
private Socket _socket;
private ReceiveCallbackDelegate _receiveCallback;
public IPEndPoint Endpoint => (IPEndPoint)_socket.RemoteEndPoint;
private readonly ILogger _logger;
public TcpConnectionState(ILogger<TcpConnectionState> logger, Socket socket, byte[] buffer, IDevice device, ReceiveCallbackDelegate receiveCallback, DisconnectCallbackDelegate disconnectCallback):
base(device, disconnectCallback)
{
_logger = Validate.IsNotNull(logger, nameof(logger));
_socket = socket;
_buffer = buffer;
_receiveCallback = receiveCallback;
BeginReceive();
}
public bool IsConnected()
{
try
{
return !(_socket.Poll(1, SelectMode.SelectRead) && _socket.Available == 0);
}
catch (SocketException)
{
return false;
}
}
private void BeginReceive()
{
try
{
_socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, BeginReceiveCallback, null);
}
catch (SocketException)
{
Disconnect();
}
}
private void BeginReceiveCallback(IAsyncResult ar)
{
try
{
int bytesReceived = _socket.EndReceive(ar);
if (bytesReceived > 0)
{
var data = _buffer.Take<byte>(bytesReceived).ToArray<byte>();
_receiveCallback(data, null, _socket.RemoteEndPoint);
}
BeginReceive();
}
catch (SocketException ex)
{
if (ex.SocketErrorCode == SocketError.ConnectionReset)
{
_logger.LogInformation(ex.Message);
}
else
{
_logger.LogError(ex, string.Empty);
}
Disconnect();
}
catch(Exception ex)
{
_logger.LogError(ex, string.Empty);
Disconnect();
}
}
public void Send(byte[] data)
{
try
{
_socket.BeginSend(data, 0, data.Length, SocketFlags.None, BeginSendCallback, null);
_logger.LogTrace(data, d => $"Send {BitConverter.ToString(d)}");
_logger.LogDebug($"Sent {data.Length} bytes");
}
catch(SocketException ex)
{
if (ex.SocketErrorCode == SocketError.ConnectionReset)
{
_logger.LogInformation(ex.Message);
}
else
{
_logger.LogError(ex, string.Empty);
}
Disconnect();
}
catch (Exception ex)
{
_logger.LogError(ex, string.Empty);
Disconnect();
}
}
private void BeginSendCallback(IAsyncResult ar)
{
var bytesSent = _socket.EndSend(ar);
}
public override void Disconnect()
{
_socket.BeginDisconnect(false, BeginDisconnectCallback, null);
}
private void BeginDisconnectCallback(IAsyncResult ar)
{
_logger.LogDebug("Disconnect");
base.Disconnect();
}
}

Client disconnected, but server don't see it

so i was making a Tcp Server, when i got a problem while a client is disconnecting. Exception is being throwed, but it looks like that server don't see it. And it don't remove the disconnected client from list. Here is code:
public void Read(IAsyncResult ar, TcpClient PL)
{
try
{
{
BytesRead[PL] = PL.GetStream().EndRead(ar);
}
if (BytesRead[PL] < 1)
{
throw new SocketException();
}
else
{
while (true)
{
packets++; break;
}
}
}
catch (Exception x)
{
if ((x.Message.Contains("Client") && x.Message.Contains("Disconnected")) || x is SocketException || x is EndOfStreamException || x is IOException) //|| x.InnerException.GetType() == typeof(IOException))
{
throw;
}
else
{
System.Console.WriteLine(x.ToString());
}
}
}
It occurs when client closes program or when it's killed by task manager
Here is where method Read has been used.
private void HandleClient(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream ns = tcpClient.GetStream();
while (true)
{
try
{
while ((true))
{
{
try
{
}
catch (SocketException ex)
{
if ((ex.Message.Contains("Client") && ex.Message.Contains("Disconnected")) || ex is SocketException)
{
throw;
}
}
try
{
{
}
}
catch (Exception ex)
{
}
}
}
}
catch (SocketException ex)
{
if (((ex.Message.Contains("Client") && ex.Message.Contains("Disconnected"))) || ex is SocketException )
{
clients.Remove(tcpClient);
}
else
{
System.Console.WriteLine(ex.ToString());
}
}
}
}
Here is the TcpListener Initialization
public void Server1()
{
timer = new Timer(new TimerCallback(MultipleCheck), null, 0, 500);
listener = new TcpListener(IPAddress.Parse("25.75.22.56"), 29339);
listenThread = new Thread(new ThreadStart(ListenForClients));
listenThread.Start();
}
And here is method where it accepts the TcpClient
private void ListenForClients()
{
listener.Start();
while (true)
{
System.Console.Title = "Server : " + clients.Count.ToString();
if (!LineStarted)
{
System.Console.WriteLine("Server started on port 29339");
LineStarted = true;
}
System.Console.WriteLine("Connection Request");
TcpClient client = listener.AcceptTcpClient();
if (client.Connected)
{
clients.Add(client);
System.Console.WriteLine("New Client Connected");
//if (threads.ContainsKey(client))
{
threads[client].Start(client);
}
counter++;
}
}
}
Before the threads[tcpClient].Abort(); put try instruction
try
{
//Removing Client from list and notifying connected users about disconnected
//client from list
}
catch
{
}
//And after Abort the thread to avoid the exception of thread aborting being
//thrown too early
threads[tcpClient].Abort();
threads.Remove(tcpClient);

C# async SocketException while binding

I am working on a client-server application on C# using async sockets. As I listen for connections, I keep getting this error
An unhandled exception of type 'System.Net.Sockets.SocketException'
occurred in System.dll
Additional information: Only one usage of each socket address (protocol/network address/port) is normally permitted
This is the line where this exception happens:
_listener.Bind(new IPEndPoint(0, port));
The code is under Listener.Start(int port). In the main program, here's how I call the method:
void btnListen_Click(object sender, EventArgs e)
{
_listener = new Listener();
_listener.Accepted += new Listener.SocketAcceptedHandler(listener_Accepted);
_listener.Start(8192);
}
I am testing both the client and server applications in my PC.
Here's the Listener class.
namespace serverPC
{
class Listener
{
public delegate void SocketAcceptedHandler(Socket e);
public event SocketAcceptedHandler Accepted;
Socket _listener;
public int Port;
public bool Running
{
get;
private set;
}
public Listener() {Port = 0;}
public void Start(int port)
{
if (Running)
return;
_listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_listener.Bind(new IPEndPoint(0, port)); // This is where the SocketException error occurs
_listener.Listen(0);
_listener.BeginAccept(acceptedCallback, null);
Running = true;
}
public void Stop()
{
if (!Running)
return;
_listener.Close();
Running = false;
}
void acceptedCallback(IAsyncResult ar)
{
try
{
Socket s = _listener.EndAccept(ar);
if (Accepted != null)
{
Accepted(s);
}
}
catch
{
}
if (Running)
{
try
{
_listener.BeginAccept(acceptedCallback, null);
}
catch
{
}
}
}
}
}
Here's the Client class.
namespace serverPC
{
struct ReceiveBuffer
{
public const int BUFFER_SIZE = 1024;
public byte[] Buffer;
public int ToReceive;
public MemoryStream BufStream;
public ReceiveBuffer(int toRec)
{
Buffer = new byte[BUFFER_SIZE];
ToReceive = toRec;
BufStream = new MemoryStream(toRec);
}
public void Dispose()
{
Buffer = null;
ToReceive = 0;
Close();
if (BufStream != null)
BufStream.Dispose();
}
public void Close()
{
if (BufStream != null && BufStream.CanWrite)
{
BufStream.Close();
}
}
}
class Client
{
byte[] lenBuffer;
ReceiveBuffer buffer;
Socket _socket;
public IPEndPoint EndPoint
{
get
{
if (_socket != null && _socket.Connected)
{
return (IPEndPoint)_socket.RemoteEndPoint;
}
return new IPEndPoint(IPAddress.None, 0);
}
}
public delegate void DisconnectedEventHandler(Client sender);
public event DisconnectedEventHandler Disconnected;
public delegate void DataReceivedEventHandler(Client sender, ReceiveBuffer e);
public event DataReceivedEventHandler DataReceived;
public Client(Socket s)
{
_socket = s;
lenBuffer = new byte[4];
}
public void Close()
{
if (_socket != null)
{
_socket.Disconnect(false);
_socket.Close();
}
buffer.Dispose();
_socket = null;
lenBuffer = null;
Disconnected = null;
DataReceived = null;
}
public void ReceiveAsync()
{
_socket.BeginReceive(lenBuffer, 0, lenBuffer.Length, SocketFlags.None, receiveCallback, null);
}
void receiveCallback(IAsyncResult ar)
{
try
{
int rec = _socket.EndReceive(ar);
if (rec == 0)
{
if (Disconnected != null)
{
Disconnected(this);
return;
}
if (rec != 4)
{
throw new Exception();
}
}
}
catch (SocketException se)
{
switch (se.SocketErrorCode)
{
case SocketError.ConnectionAborted:
case SocketError.ConnectionReset:
if (Disconnected != null)
{
Disconnected(this);
return;
}
break;
}
}
catch (ObjectDisposedException)
{
return;
}
catch (NullReferenceException)
{
return;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return;
}
buffer = new ReceiveBuffer(BitConverter.ToInt32(lenBuffer, 0));
_socket.BeginReceive(buffer.Buffer, 0, buffer.Buffer.Length, SocketFlags.None, receivePacketCallback, null);
}
void receivePacketCallback(IAsyncResult ar)
{
int rec = _socket.EndReceive(ar);
if (rec <= 0)
{
return;
}
buffer.BufStream.Write(buffer.Buffer, 0, rec);
buffer.ToReceive -= rec;
if(buffer.ToReceive > 0)
{
Array.Clear(buffer.Buffer, 0, buffer.Buffer.Length);
_socket.BeginReceive(buffer.Buffer, 0, buffer.Buffer.Length, SocketFlags.None, receivePacketCallback, null);
return;
}
if (DataReceived != null)
{
buffer.BufStream.Position = 0;
DataReceived(this, buffer);
}
buffer.Dispose();
ReceiveAsync();
}
}
}
Why do I get the SocketException error? Any help is appreciated. Thanks!
So the obvious things to check - Something is already listening on port 8192 or there's some other reason why your machine would reject your program opening that port (firewalls, etc).
The other problem is while you are blocking binding twice with the "Running" check, you're only doing that for the instance of listener - hitting the button will create a whole new listener and attempt to have it listen on port 8192 - which since you already have a listener bound there, will fail with that exception.

Android TCP communication error

I am very new to Android Programming .
My code in android is as follows
public class AndroidClient extends Activity {
EditText textOut;
TextView textIn;
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_client);
textOut = (EditText)findViewById(R.id.textout);
Button buttonSend = (Button)findViewById(R.id.send);
textIn = (TextView)findViewById(R.id.textin);
buttonSend.setOnClickListener(buttonSendOnClickListener);
}
Button.OnClickListener buttonSendOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new BackgroundDataTask().execute("");
}};
public class BackgroundDataTask extends AsyncTask<String,String,String> {
private Exception ex;
#Override
protected String doInBackground(String... urls) {
try {
socket = new Socket("10.20.50.68", 8888);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(textOut.getText().toString());
textIn.setText(dataInputStream.readUTF());
socket = serverSocket.accept();
textIn.setText(socket.getInetAddress().toString());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return "";
}
}
}
I have a server in C# Code
The code listens to the port and writes the output
However this only works for the first time when I type in the text and click Send the code is received at Server end and I can see the ouptput in the console,But the value is not received after that .So how can i keep this socket running ? What am I missing?
Thank you All
try this
create a class client.java
public class client{
Socket socket;
int Port;
InetAddress serverIp;
public boolean connection;
public client(String ip, int port) {
// TODO Auto-generated constructor stub
try {
serverIp = InetAddress.getByName(ip);
Port = port;
connect();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
connection = false;
}
}
public void connect(){
try {
System.out.println("wait connection client "+serverIp+" "+Port);
socket = new Socket(serverIp, Port);
connection = true;
} catch (IOException e) {
//e.printStackTrace();
connection = false;
}
}
public boolean send(String message) throws IOException {
byte[] data=message.getBytes();
OutputStream out = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
int len = data.length;
dos.writeInt(len);
if (len > 0) {
dos.write(data, 0, len);
}
return true;
}
public String read() {
InputStream in = null;
try {
in = socket.getInputStream();
} catch (IOException e) {
connection=false;
e.printStackTrace();
}
DataInputStream dis = new DataInputStream(in);
try {
int len = dis.readInt();
byte[] data = new byte[len];
if (len > 0) {
dis.readFully(data);
}
String result = new String(data, 0, data.length);
return result;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
connection=false;
}
return "";
}
and create a object of client.java in your activity onCreate
client con=new client("10.20.50.68", 8888);
and use con.send("your_data") to sent and String data=con.read(); to receive data...
if you want asynchronous listening of data in socket, use thread

BlockingCollection having issues with byte arrays

I am having an issue where an object with a byte[20] is being passed into a BlockingCollection on one thread and another thread returning the object with a byte[0] using BlockingCollection.Take(). I think this is a threading issue but I do not know where or why this is happening considering that BlockingCollection is a concurrent collection.
Sometimes on thread2, myclass2.mybytes equals byte[0]. Any information on how to fix this is greatly appreciated.
[EDIT] The original code.
I removed the above code that seemed to run just fine so I took the time to go through my original code and post it.
MessageBuffer.cs
public class MessageBuffer : BlockingCollection<Message>
{
}
In the class that has Listener() and ReceivedMessageHandler(object messageProcessor)
private MessageBuffer RecievedMessageBuffer;
On Thread1
private void Listener()
{
while (this.IsListening)
{
try
{
Message message = Message.ReadMessage(this.Stream, this);
if (message != null)
{
this.RecievedMessageBuffer.Add(message);
}
}
catch (IOException ex)
{
if (!this.Client.Connected)
{
this.OnDisconnected();
}
else
{
Logger.LogException(ex.ToString());
this.OnDisconnected();
}
}
catch (Exception ex)
{
Logger.LogException(ex.ToString());
this.OnDisconnected();
}
}
}
Message.ReadMessage(NetworkStream stream, iTcpConnectClient client)
public static Message ReadMessage(NetworkStream stream, iTcpConnectClient client)
{
int ClassType = -1;
Message message = null;
try
{
ClassType = stream.ReadByte();
if (ClassType == -1)
{
return null;
}
if (!Message.IDTOCLASS.ContainsKey((byte)ClassType))
{
throw new IOException("Class type not found");
}
message = Message.GetNewMessage((byte)ClassType);
message.Client = client;
message.ReadData(stream);
if (message.Buffer.Length < message.MessageSize + Message.HeaderSize)
{
return null;
}
}
catch (IOException ex)
{
Logger.LogException(ex.ToString());
throw ex;
}
catch (Exception ex)
{
Logger.LogException(ex.ToString());
//throw ex;
}
return message;
}
On Thread2
private void ReceivedMessageHandler(object messageProcessor)
{
if (messageProcessor != null)
{
while (this.IsListening)
{
Message message = this.RecievedMessageBuffer.Take();
message.Reconstruct();
message.HandleMessage(messageProcessor);
}
}
else
{
while (this.IsListening)
{
Message message = this.RecievedMessageBuffer.Take();
message.Reconstruct();
message.HandleMessage();
}
}
}
PlayerStateMessage.cs
public class PlayerStateMessage : Message
{
public GameObject PlayerState;
public override int MessageSize
{
get { return 12; }
}
public PlayerStateMessage()
: base()
{
this.PlayerState = new GameObject();
}
public PlayerStateMessage(GameObject playerState)
{
this.PlayerState = playerState;
}
public override void Reconstruct()
{
this.PlayerState.Poisiton = this.GetVector2FromBuffer(0);
this.PlayerState.Rotation = this.GetFloatFromBuffer(8);
base.Reconstruct();
}
public override void Deconstruct()
{
this.CreateBuffer();
this.AddToBuffer(this.PlayerState.Poisiton, 0);
this.AddToBuffer(this.PlayerState.Rotation, 8);
base.Deconstruct();
}
public override void HandleMessage(object messageProcessor)
{
((MessageProcessor)messageProcessor).ProcessPlayerStateMessage(this);
}
}
Message.GetVector2FromBuffer(int bufferlocation)
This is where the exception is thrown because this.Buffer is byte[0] when it should be byte[20].
public Vector2 GetVector2FromBuffer(int bufferlocation)
{
return new Vector2(
BitConverter.ToSingle(this.Buffer, Message.HeaderSize + bufferlocation),
BitConverter.ToSingle(this.Buffer, Message.HeaderSize + bufferlocation + 4));
}
So this was a hard problem to solve. As far as I know, I was just receiving random bytes so I changed up my "Message" quite a bit. there is now a header buffer and a data buffer. The entire message is encapsulated with a beginning marker and an ending marker while the header and data buffers are each encapsulated by different markers. this has allowed me to tell when I have received bad data and can discard the message. If the message does get discarded, on the next message read, instead of just checking if the first 4 bytes received is the opening marker, it will read byte by byte until the last 4 bytes read are equal to the marker.

Categories

Resources