webcam frame in a class to serialize and send - c#

I'm trying to serialize a MessageData class and send it by network.
This class contain picture in bitmap that I need to display on a form.
The transmitted bitmap it's a frame that a webcam need to transmit several times each second by network to a WinForm.
This program it's a test and in future will be splitted in two parts, client part with receiver method and winform, and a server part with webcam and sender method.
Actually the Serializing and sending-receiving of the object-picture is not working, the winform is not showing any image if I force picture to pass from the serializing-network process instad of get it directly.
The webcam frames are managed with the Emgu.CV library, and locally it's working very well, but not by remote with the serialization sending of the frames.
All that follow is inside the namespace Idea:
[Serializable]
public class MessageData {
public MessageData(Bitmap img){
Picture = img;
}
public static Bitmap Picture { get; set; }
}
[Serializable]
public class MessageSendData {
public MessageSendData(Bitmap img){
Picture = img;
}
public static Bitmap Picture { get; set; }
}
public partial class Idea : Form
{
//declaring global variables
private Capture capture; //takes images from camera as image frames
private bool captureInProgress; // checks if capture is executing
private TcpListener ascolto;
Bitmap bitmapricevuto;
public Idea()
{
InitializeComponent();
}
private void Idea_Load(object sender, EventArgs e)
{
}
private void ProcessFrame(object sender, EventArgs arg)
{
Image<Bgr, Byte> ImageFrame = capture.QueryFrame(); //line 1
// CamImageBox.Image = byteArrayToImage(MyImageBytes(ImageFrame.ToBitmap()));
// CamImageBox.Image = ImageFrame.ToBitmap();
Thread r = new Thread(Ricevi);
r.Start();
MessageSendData.Picture = ImageFrame.ToBitmap();
Thread s = new Thread(Spedisci);
s.Start();
lock (MessageData.Picture){
CamImageBox.Image = MessageData.Picture;
}
}
private void btnStart_Click(object sender, EventArgs e)
{
#region if capture is not created, create it now
if (capture == null)
{
try
{
capture = new Capture();
}
catch (NullReferenceException excpt)
{
MessageBox.Show(excpt.Message);
}
}
#endregion
if (capture != null)
{
if (captureInProgress)
{ //if camera is getting frames then stop the capture and set button Text
// "Start" for resuming capture
btnStart.Text = "Start!"; //
Application.Idle -= ProcessFrame;
}
else
{
//if camera is NOT getting frames then start the capture and set button
// Text to "Stop" for pausing capture
btnStart.Text = "Stop";
Application.Idle += ProcessFrame;
}
captureInProgress = !captureInProgress;
}
}
private void ReleaseData()
{
if (capture != null)
capture.Dispose();
}
public static void Ricevi()
{
IPAddress address = IPAddress.Parse("127.0.0.1");
TcpListener listener = new TcpListener(address, 8585);
listener.Start();
Bitmap mia;
try
{
using (TcpClient client = listener.AcceptTcpClient())
{
NetworkStream stream = client.GetStream();
IFormatter formatter = new BinaryFormatter();
while (true)
{
lock (MessageData.Picture){
MessageData.Picture = (Bitmap)formatter.Deserialize(stream);
}
}
}
}
catch(Exception ex) { }
return;
}
public static void Spedisci()
{
IPAddress address = IPAddress.Parse("127.0.0.1");
TcpClient client = new TcpClient();
try
{
client.Connect(address, 8585);
// Retrieve the network stream.
NetworkStream stream = client.GetStream();
IFormatter formatter = new BinaryFormatter();
while(true)
{
lock (MessageSendData.Picture) {
formatter.Serialize(stream, MessageSendData.Picture);
//Thread.Sleep(1000);
}
}
}
catch (Exception ex) { }
}
/*
public byte[] MyImageBytes(Image MyImage)
{
ImageConverter converter = new ImageConverter();
return (byte[])converter.ConvertTo(MyImage, typeof(byte[]));
}
public Image byteArrayToImage(byte[] bytesArr)
{
MemoryStream memstr = new MemoryStream(bytesArr);
Image img = Image.FromStream(memstr);
return img;
}
*/
}
}
'
I've realized two methods: 1-First method convert the bitmap in a byte array. 2-Second method convert the byte array in a bitmap. Testing them directly without send the converted bytes by tcp network I see that all software are working. Now I've created two methods "Invia" and "Ricevi" that are sending and receiving with async methods the bytearrays by spliting them in stream of a length of 1024 each. My issue on compiling it's about the Async Task methods returned types. How to fix this threads Task async issues?
'
private void ProcessFrame(object sender, EventArgs arg)
{
Image<Bgr, Byte> ImageFrame = capture.QueryFrame();
invia(MyImageBytes(ImageFrame.ToBitmap()));
CamImageBox.Image = ricevi();
}
public byte[] MyImageBytes(Image MyImage)
{
ImageConverter converter = new ImageConverter();
return (byte[])converter.ConvertTo(MyImage, typeof(byte[]));
}
'
Send (Invia) and Receive(Ricevi) methods last version here showed below are using the chars converted to bytes array and appended to the bitmap bytes array for send and receive the bitmap. Actually I've issues during compiling:
public static void invia(byte[] bytetosend)
{
// Data buffer for incoming data.
byte[] bytes = new byte[1024];
// Connect to a remote device.
try {
// Establish the remote endpoint for the socket.
// This example uses port 11000 on the local computer.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress,11000);
// Create a TCP/IP socket.
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp );
// Connect the socket to the remote endpoint. Catch any errors.
try {
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}",
sender.RemoteEndPoint.ToString());
// Encode the data string into a byte array.
var mahByteArray = new ArrayList<byte>();
mahByteArray.AddRange(bytetosend);
string eof = "<EOF>";
mahByteArray.Insert(0, Convert.ToByte(eof)); // Adds eof bytes to the beginning.
byte[] msg = mahByteArray.ToArray();
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Echoed test = {0}",
Encoding.ASCII.GetString(bytes,0,bytesRec));
// Release the socket.
sender.Shutdown(SocketShutdown.Both);
sender.Close();
} catch (ArgumentNullException ane) {
Console.WriteLine("ArgumentNullException : {0}",ane.ToString());
} catch (SocketException se) {
Console.WriteLine("SocketException : {0}",se.ToString());
} catch (Exception e) {
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
} catch (Exception e) {
Console.WriteLine( e.ToString());
}
}
public static void ricevi()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
var scambioArray = new ArrayList();
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
// Start listening for connections.
while (true)
{
Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
string eofr = "<EOF>";
byte[] trova = Convert.ToByte(eofr);
// An incoming connection needs to be processed.
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
if (bytes.IndexOf(trova))
{
var mahByteArray = new ArrayList();
mahByteArray.AddRange(bytes);
mahByteArray.Remove(trova);
bytes = mahByteArray.ToArray();
break;
}
scambioArray.AddRange(bytes);
}
// Echo the data back to the client.
byte[] msg = scambioArray.ToArray();
MessageData.Picture = byteArrayToImage(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}

Try something like this
using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public static void invia(byte[] bytetosend)
{
// Data buffer for incoming data.
byte[] bytes = new byte[1024];
// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
// This example uses port 11000 on the local computer.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint. Catch any errors.
try
{
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}",
sender.RemoteEndPoint.ToString());
// Encode the data string into a byte array.
var mahByteArray = new List<byte>();
mahByteArray.AddRange(bytetosend);
string eof = "<EOF>";
mahByteArray.Insert(0, Convert.ToByte(eof)); // Adds eof bytes to the beginning.
byte[] msg = mahByteArray.ToArray();
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Echoed test = {0}",
Encoding.ASCII.GetString(bytes, 0, bytesRec));
// Release the socket.
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
catch (ArgumentNullException ane)
{
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
}
catch (SocketException se)
{
Console.WriteLine("SocketException : {0}", se.ToString());
}
catch (Exception e)
{
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public void ricevi()
{
// Data buffer for incoming data.
List<byte> bytes = (new Byte[1024]).ToList();
List<byte> scambioArray = new List<byte>();
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
// Start listening for connections.
while (true)
{
Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
string eofr = "<EOF>";
List<byte> trova = Encoding.UTF8.GetBytes(eofr).ToList();
// An incoming connection needs to be processed.
while (true)
{
bytes = (new byte[1024]).ToList();
int bytesRec = handler.Receive(bytes.ToArray());
if (bytes.Contains(trova[0]))
{
List<byte> mahByteArray = new List<byte>();
mahByteArray.AddRange(bytes);
mahByteArray.Remove(trova[0]);
bytes = mahByteArray.ToArray().ToList();
break;
}
scambioArray.AddRange(bytes);
}
// Echo the data back to the client.
byte[] msg = scambioArray.ToArray();
MemoryStream stream = new MemoryStream(msg);
MessageData.Image = Image.FromStream(stream);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
​

Related

Adding Security To Chat Client

So this is my basic chat program which allows user to add its own IP and receive an IP, plus custom ports to communicate.
In the windows forms design I have:
Textbox --- textLocalIp
Textbox --- textLocalPort
Textbox --- textFriendIp
Textbox --- textFriendPort
Textbox --- textMessage
Listbox --- listMessage
Button --- Start
Button --- Send
So this is a very basic client but what I want help with is making it secure/more secure because security right now is not good.
Maybe like a tunnel with different IP's so that you don't have to know the receivers IP, just a IP they provide which then sends it to them or whatever?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace Client
{
public partial class Form1 : Form
{
Socket sck;
EndPoint epLocal, epRemote;
public Form1()
{
InitializeComponent();
sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
textLocalIp.Text = GetLocalIP();
textFriendIp.Text = GetLocalIP();
}
private string GetLocalIP()
{
IPHostEntry host;
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
return "127.0.0.1";
}
private void MessageCallBack(IAsyncResult aResult)
{
try
{
int size = sck.EndReceiveFrom(aResult, ref epRemote);
if (size > 0)
{
byte[] recievedData = new byte[1464];
recievedData = (byte[])aResult.AsyncState;
ASCIIEncoding eEncoding = new ASCIIEncoding();
string receivedMessage = eEncoding.GetString(recievedData);
listMessage.Items.Add("Sender: "+receivedMessage);
}
byte[] buffer = new byte[1500];
sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
}
catch (Exception exp)
{
MessageBox.Show(exp.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
try
{
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
byte[] msg = new byte[1500];
msg = enc.GetBytes(textMessage.Text);
sck.Send(msg);
listMessage.Items.Add("Local:" + textMessage.Text);
textMessage.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void start_Click(object sender, EventArgs e)
{
try
{
epLocal = new IPEndPoint(IPAddress.Parse(textLocalIp.Text), Convert.ToInt32(textLocalPort.Text));
sck.Bind(epLocal);
epRemote = new IPEndPoint(IPAddress.Parse(textFriendIp.Text), Convert.ToInt32(textFriendPort.Text));
sck.Connect(epRemote);
byte[] buffer = new byte[1500];
sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
start.Text = "Connected";
start.Enabled = false;
send.Enabled = true;
textMessage.Focus();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
It is more difficult to implement socket communication security using channels. So I suggest you encrypt the IP and transmission content.
For IP encryption, you can set the Passwordchar attribute of the TextBox to *.
For transmission content, you can encrypt it with an encryption algorithm.
The following code implements the communication between a server and multiple clients, and you can perform encryption on this basis.
Server:
namespace Server
{
class Program
{
private static byte[] result = new byte[1024];
private static int myProt = 8885;
static Socket serverSocket;
static void Main(string[] args)
{
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(new IPEndPoint(IPAddress.Any, myProt));
serverSocket.Listen(10); //Set up to 10 queued connection requests
Console.WriteLine("Start listening {0} successfully", serverSocket.LocalEndPoint.ToString());
Thread myThread = new Thread(ListenClientConnect);
myThread.Start();
Console.ReadLine();
}
/// <summary>
/// Listen for Client connections
/// </summary>
private static void ListenClientConnect()
{
while (true)
{
Socket clientSocket = serverSocket.Accept();
clientSocket.Send(Encoding.ASCII.GetBytes("Server Say Hello"));
Thread receiveThread = new Thread(ReceiveMessage);
receiveThread.Start(clientSocket);
}
}
/// <summary>
/// receive data
/// </summary>
/// <param name="clientSocket"></param>
private static void ReceiveMessage(object clientSocket)
{
Socket myClientSocket = (Socket)clientSocket;
while (true)
{
try
{
int receiveNumber = myClientSocket.Receive(result);
Console.WriteLine("Receive client {0} message {1}", myClientSocket.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(result, 0, receiveNumber));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
myClientSocket.Shutdown(SocketShutdown.Both);
myClientSocket.Close();
break;
}
}
}
}
}
Client:
namespace Client
{
class Program
{
private static byte[] result = new byte[1024];
static void Main(string[] args)
{
IPAddress ip = IPAddress.Parse("127.0.0.1");
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
clientSocket.Connect(new IPEndPoint(ip, 8885));
Console.WriteLine("Successfully connected to the server");
}
catch
{
Console.WriteLine("Failed to connect to the server, please press Enter to exit!");
return;
}
//Receive data through clientSocket
int receiveLength = clientSocket.Receive(result);
Console.WriteLine("Server:{0}", Encoding.ASCII.GetString(result, 0, receiveLength));
//Send data through clientSocket
for (int i = 0; i <3; i++)
{
try
{
Thread.Sleep(1000);
string sendMessage = "client send Message Hellp" + DateTime.Now;
clientSocket.Send(Encoding.ASCII.GetBytes(sendMessage));
Console.WriteLine("Client:{0}" + sendMessage);
}
catch
{
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
break;
}
}
Console.WriteLine("After sending, press Enter to exit");
Console.ReadLine();
}
}
}

clients cannot establish connection after certain time even if the socket server is running

I have a console application which acts as a socket server. It should accept data 24/7 from a number of clients, but issue is that the clients cannot establish connection after sometime (not constant). after closing & opening the connection works & it continues to next point of time.
Server
public static void ExecuteServer()
{
int portNumber = 11111;
string _responseMessageToClient = "";
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddr, portNumber);
// Creation TCP/IP Socket using
// Socket Class Costructor
Socket listener = new Socket(ipAddr.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
bool doBroadCast = false;
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
while (true)
{
try`enter code here`
{
Socket clientSocket = listener.Accept();
// Data buffer
byte[] bytes = new Byte[1024*2];//2048
string data = null;
while (true)
{
try
{
if (clientSocket.Connected)
{
int numByte = clientSocket.Receive(bytes);
data += Encoding.ASCII.GetString(bytes,
0, numByte);
if (data.IndexOf("!") > -1)
break;
}
else
{
Console.WriteLine("Disconnected {0}", clientSocket.LocalEndPoint);
break;
}
}
catch (Exception e)
{
//ErrorLogProvider.Save(e);
Console.WriteLine(e.ToString());
break;
}
}
Console.WriteLine("Text received -> {0} ", data);
if (clientSocket.Connected)
{
clientSocket.Send(message);
}
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
}
catch (Exception e)
{
}
}
}
catch (Exception e)
{
}
}
This server has to be running continuously - Client code given below
static void ExecuteClient()
{
try
{
// Establish the remote endpoint
// for the socket. This example
// uses port 11111 on the local
// computer.
int portNumber = 11111;
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddr, portNumber);
// Creation TCP/IP Socket using
// Socket Class Costructor
Socket sender = new Socket(ipAddr.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
long i = 0;
try
{
//while (i < 10)
//{
// Connect Socket to the remote
// endpoint using method Connect()
sender.Connect(localEndPoint);
// We print EndPoint information
// that we are connected
Console.WriteLine("Socket connected to -> {0} ",
sender.RemoteEndPoint.ToString());
// Creation of messagge that
// we will send to Server
byte[] messageSent = Encoding.ASCII.GetBytes("^check!");
int byteSent = sender.Send(messageSent);
// Data buffer
byte[] messageReceived = new byte[1024];
// We receive the messagge using
// the method Receive(). This
// method returns number of bytes
// received, that we'll use to
// convert them to string
int byteRecv = sender.Receive(messageReceived);
Console.WriteLine("Message from Server -> {0}",
Encoding.ASCII.GetString(messageReceived,
0, byteRecv));
//}
// Close Socket using
// the method Close()
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
// Manage of Socket's Exceptions
catch (ArgumentNullException ane)
{
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
}
catch (SocketException se)
{
Console.WriteLine("SocketException : {0}", se.ToString());
}
catch (Exception e)
{
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
I've got this code somewhere from SO if I remember that correctly.
LoopClients just checks for new clients and handles them by spawning a new thread.
class Server {
private TcpListener _server;
private Boolean _isRunning = true;
private int m_Port = 12001;
private Thread m_ServerThread;
public Server (int p_Port) {
_server = new TcpListener(IPAddress.Any, m_Port);
_server.Start( );
m_ServerThread = new Thread(new ThreadStart(LoopClients));
m_ServerThread.Start( );
}
public void ShutdownServer() {
_isRunning = false;
}
public void LoopClients ( ) {
while ( _isRunning ) {
// wait for client connection
TcpClient newClient = _server.AcceptTcpClient( );
// client found.
// create a thread to handle communication
Thread t = new Thread(new ParameterizedThreadStart(HandleClient));
t.Start(newClient);
}
}
public void HandleClient (object obj) {
try {
// retrieve client from parameter passed to thread
TcpClient client = (TcpClient) obj;
// sets two streams
StreamWriter sWriter = new StreamWriter(client.GetStream( ), Encoding.ASCII);
StreamReader sReader = new StreamReader(client.GetStream( ), Encoding.ASCII);
// you could use the NetworkStream to read and write,
// but there is no forcing flush, even when requested
String sData = null;
while ( client.Connected ) {
sData = sReader.ReadToEnd( );
if ( sData != "" )
break;
}
try {
sWriter.WriteLine("test");
} catch(Exception ex) {
Console.WriteLine(ex.Message);
}
sWriter.Dispose( );
sReader.Dispose( );
sWriter = null;
sReader = null;
} catch ( IOException ioe ) {
}
}
}
Client is somewhat shorter. I've got to shorten the code a bit here.
Client:
private void sendDataViaTCP () {
TcpClient l_Client = new TcpClient();
l_Client.Connect(IP, Port);
Stream l_Stream = l_Client.GetStream( );
StreamWriter l_SW = new StreamWriter(l_Stream);
StreamReader l_SR = new StreamReader(l_SW.BaseStream);
try {
l_SW.WriteLine(Msg);
l_SW.Flush( );
String l_IncomingData;
while ( ( l_IncomingData = l_SR.ReadToEnd()) != "") {
AddLineToLog(l_IncomingData);
}
} finally {
l_SW.Close( );
}
}

C# How to do to send more message to Server with Client?

Im writing a Client Server Socket C# with TCP protocoll to create sort of "Client Ask, Server Answer" But when I Execute first command my client close. I should put while somewhere but I don't know where. here is the code:
CLIENT
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SynchronousSocketClient
{
public static void StartClient()
{
// Data buffer for incoming data.
byte[] bytes = new byte[1024];
// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
// This example uses port 11000 on the local computer.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint. Catch any errors.
try
{
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}", sender.RemoteEndPoint.ToString());
Console.WriteLine("Insert text to send to server");
String a = Console.ReadLine(); //This is a test<EOF>
// Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes(a);
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Echoed test = {0}", Encoding.ASCII.GetString(bytes, 0, bytesRec));
// Release the socket.
//sender.Shutdown(SocketShutdown.Both);
//sender.Close();
}
catch (ArgumentNullException ane)
{
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
}
catch (SocketException se)
{
Console.WriteLine("SocketException : {0}", se.ToString());
}
catch (Exception e)
{
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static int Main(String[] args)
{
StartClient();
//To avoid Prompt disappear
Console.Read();
return 0;
}
}
SERVER
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Collections;
using System.IO;
//using System.Diagnostics;
public class SynchronousSocketListener
{
// Incoming data from the client.
public static string data = null;
public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
byte[] msg = null;
// Start listening for connections.
while (true)
{
Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
data = null;
// An incoming connection needs to be processed.
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.Equals("ping"))
{
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
msg = Encoding.ASCII.GetBytes("pong");
handler.Send(msg);
break;
}
if (data.Equals("dir"))
{
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
msg = Encoding.ASCII.GetBytes(System.AppDomain.CurrentDomain.BaseDirectory);
handler.Send(msg);
break;
}
if (data.Equals("files"))
{
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);
String files = "";
string[] fileEntries = Directory.GetFiles(System.AppDomain.CurrentDomain.BaseDirectory);
foreach (string fileName in fileEntries)
files += ProcessFile(fileName);
// Echo the data back to the client.
msg = Encoding.ASCII.GetBytes(files);
handler.Send(msg);
break;
}
}
// Show the data on the console.
//Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
//byte[] msg = Encoding.ASCII.GetBytes(data);
//handler.Send(msg);
//handler.Shutdown(SocketShutdown.Both);
//handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public static String ProcessFile(string path)
{
return path += "\n\n" + path;
}
public static void ProcessDirectory(string targetDirectory)
{
// Process the list of files found in the directory.
string[] fileEntries = Directory.GetFiles(targetDirectory);
foreach (string fileName in fileEntries)
ProcessFile(fileName);
// Recurse into subdirectories of this directory.
string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
foreach (string subdirectory in subdirectoryEntries)
ProcessDirectory(subdirectory);
}
public static int Main(String[] args)
{
StartListening();
return 0;
}
}
Now If you copy paste this code and execute Server and then Client, you can write something into CLient prompt and get an answers but at 2 attempt CLient close because there is no while that continues the process! I tried put while out of try and into but code crashed! An Help would be appreciate an help or solution is the same, just get an answer :)
Thank you everyone
I have limited knowledge working with sockets. However I know you should only call the following once:
Socket handler = listener.Accept();
I added a while loop under the above line and also removed your break statements at the end of your if conditions.
So the new code becomes:
CLIENT
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SynchronousSocketClient
{
public static void StartClient()
{
// Data buffer for incoming data.
byte[] bytes = new byte[1024];
// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
// This example uses port 11000 on the local computer.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint. Catch any errors.
try
{
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}", sender.RemoteEndPoint.ToString());
while (true)
{
Console.WriteLine("Insert text to send to server");
String a = Console.ReadLine(); //This is a test<EOF>
// Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes(a);
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Echoed test = {0}", Encoding.ASCII.GetString(bytes, 0, bytesRec));
}
// Release the socket.
//sender.Shutdown(SocketShutdown.Both);
//sender.Close();
}
catch (ArgumentNullException ane)
{
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
}
catch (SocketException se)
{
Console.WriteLine("SocketException : {0}", se.ToString());
}
catch (Exception e)
{
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static int Main(String[] args)
{
StartClient();
//To avoid Prompt disappear
Console.Read();
return 0;
}
}
SERVER
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Collections;
using System.IO;
//using System.Diagnostics;
public class SynchronousSocketListener
{
// Incoming data from the client.
public static string data = null;
public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and
// listen for incoming connections.
while (true)
{
try
{
//if (!listener.IsBound)
//{
listener.Bind(localEndPoint);
//}
listener.Listen(10);
byte[] msg = null;
// Start listening for connections.
while (true)
{
Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
while (true)
{
data = null;
// An incoming connection needs to be processed.
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.Equals("ping"))
{
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
msg = Encoding.ASCII.GetBytes("pong");
handler.Send(msg);
//break;
}
if (data.Equals("dir"))
{
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
msg = Encoding.ASCII.GetBytes(System.AppDomain.CurrentDomain.BaseDirectory);
handler.Send(msg);
//break;
}
if (data.Equals("files"))
{
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);
String files = "";
string[] fileEntries = Directory.GetFiles(System.AppDomain.CurrentDomain.BaseDirectory);
foreach (string fileName in fileEntries)
files += ProcessFile(fileName);
// Echo the data back to the client.
msg = Encoding.ASCII.GetBytes(files);
handler.Send(msg);
//break;
}
}
// Show the data on the console.
//Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
//byte[] msg = Encoding.ASCII.GetBytes(data);
//handler.Send(msg);
//handler.Shutdown(SocketShutdown.Both);
//handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public static String ProcessFile(string path)
{
return path += "\n\n" + path;
}
public static void ProcessDirectory(string targetDirectory)
{
// Process the list of files found in the directory.
string[] fileEntries = Directory.GetFiles(targetDirectory);
foreach (string fileName in fileEntries)
ProcessFile(fileName);
// Recurse into subdirectories of this directory.
string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
foreach (string subdirectory in subdirectoryEntries)
ProcessDirectory(subdirectory);
}
public static int Main(String[] args)
{
StartListening();
return 0;
}
}

tcp socket asynchronous communication

`
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;
namespace ServerSocket
{
class Class1
{
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();
}
public class AsynchronousSocketListener
{
// Thread signal.
public static ManualResetEvent allDone = new ManualResetEvent(false);
public AsynchronousSocketListener()
{
}
public 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.1.89");
//IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 8095);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(100);
while (true)
{
// Set the event to nonsignaled state.
allDone.Reset();
// Start an asynchronous socket to listen for connections.
MessageBox.Show("Waiting for a connection...");
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener);
//TcpListener tcpListener = new TcpListener(ipAddress, 8095);
//tcpListener.Start();
// Wait until a connection is made before continuing.
allDone.WaitOne();
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
MessageBox.Show("\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);
// 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.IndexOf("<EOF>") > -1)
{
// All the data has been read from the
// client. Display it on the console.
MessageBox.Show(string.Concat("Read bytes from socket. \n Data :",
content.Length, content));
// Echo the data back to the client.
Send(handler, content);
}
else
{
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
}
}
private static void Send(Socket handler, String data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
handler.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), handler);
}
private static void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket handler = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = handler.EndSend(ar);
MessageBox.Show(string.Concat("Sent bytes to client.", bytesSent));
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
//public static int Main(String[] args)
//{
// StartListening();
// return 0;
//}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Windows.Forms;
namespace ClientSocket
{
class Class1
{
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 256;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
public class AsynchronousClient
{
// The port number for the remote device.
public const int port = 8095;
// ManualResetEvent instances signal completion.
//set the initial state to signaled
public static ManualResetEvent connectDone =
new ManualResetEvent(false);
public static ManualResetEvent sendDone =
new ManualResetEvent(false);
public static ManualResetEvent receiveDone =
new ManualResetEvent(false);
// The response from the remote device.
public static String response = String.Empty;
public static void StartClient(string Msg)
{
// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
// The name of the
// remote device is "host.contoso.com".
//IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
IPAddress ipAddress = IPAddress.Parse("192.168.1.89");
//IPHostEntry ipHostInfo = Dns.Resolve("host.contoso.com");
//IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
// Create a TCP/IP socket.
Socket client = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
client.BeginConnect(remoteEP,
new AsyncCallback(ConnectCallback), client);
//TcpListener tcpListener = new TcpListener(ipAddress, port);
//tcpListener.Start();
connectDone.WaitOne();//Blocks the current thread until the current System.Threading.WaitHandle receives a signal.
// Send test data to the remote device.
Send(client, Msg + "<EOF>");
sendDone.WaitOne();
// Receive the response from the remote device.
Receive(client);
receiveDone.WaitOne();
// Write the response to the console.
MessageBox.Show("Response received", response);
// Release the socket.
//client.Shutdown(SocketShutdown.Both);
//client.Close();
// client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.KeepAlive, true);
}
catch (SocketException e)
{
MessageBox.Show(e.Message);
}
}
public static void ConnectCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;//Gets a user-defined object that qualifies or contains information about an
//asynchronous operation.
// Complete the connection.
client.EndConnect(ar);//Ends a pending asynchronous connection request.
MessageBox.Show(string.Concat("Socket connected to ",
client.RemoteEndPoint.ToString()));
// Signal that the connection has been made.
connectDone.Set();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
public static void Receive(Socket client)
{
try
{
// Create the state object.
StateObject state = new StateObject();
state.workSocket = client;
// Begin receiving the data from the remote device.
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
public static void ReceiveCallback(IAsyncResult ar)
{
try
{
// Retrieve the state object and the client socket
// from the asynchronous state object.
MessageBox.Show("Receivecallback");
StateObject state = (StateObject)ar.AsyncState;
Socket client = state.workSocket;
// Read data from the remote device.
int bytesRead = client.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));
// Get the rest of the data.
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
else
{
// All the data has arrived; put it in response.
if (state.sb.Length > 1)
{
response = state.sb.ToString();
}
// Signal that all bytes have been received.
receiveDone.Set();
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
public static void Send(Socket client, String data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
client.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), client);
}
public static void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = client.EndSend(ar);
MessageBox.Show(string.Concat("Sent bytes to server.", bytesSent.ToString()));
SocketConnected(client);
// Signal that all bytes have been sent.
sendDone.Set();
MessageBox.Show("Send Callback");
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
public static bool SocketConnected(Socket s)
{
bool part1 = s.Poll(1000, SelectMode.SelectRead);
bool part2 = (s.Available == 0);
if (part1 && part2)
return false;
else
return true;
}
//public static int Main(String[] args)
//{
// StartClient();
// return 0;
//}
}
}
}
`
I have tried the Asynchronous Client and Server Communication Pattern with a C# windows Application.
I have tested the Server application from different system and the Client Application on my own system.
Once I run both application same time I can receive the Message. After that I have to restart both application to send another message. But I need it can be send data for all time with out any restarting application.
One aspect that I see is that the server shuts down the socket connection after sending data to client. This means that the client needs to initiate another round of connect sequence to data exchange ( what you mention as restarting the application). Have the server to retain connection (don't close) on exchanging data.
handler.Shutdown(SocketShutdown.Both);
handler.Close();

Network Socket - just the first message always completes

i've got the following problem in a client socket (sync) / server socket (async) environment.
If I send multiple messages from the client to the server, the first one finishs without any problems and will be received by the client without issues. When I send the 2nd message, just a few bytes go through. It doesn't seem to be a client problem, because it looks the client sends the whole message all the time. The crazy thing is, if I completely stop the project on the client and start again the first message completes again, also if the server component runs through all the time.
What I want to do...
Basically, I want to transfer different objects, most xml structured through the network and receive it on the client. Therefore, I do the Serialization/Deserialization.
The basics of the following code are extended msdn examples.
//CLIENT:
class ProgramClient
{
static void Main(string[] args)
{
string rootNode = "config";
StreamReader configStream = new StreamReader(config);
XmlDocument xml = new XmlDocument();
xml.Load(configStream);
SynchronousSocketClient socket = new SynchronousSocketClient("192.168.0.1", 40001, "c:\\log", xml);
socket.StartClient();
socket.Dispose();
socket = new SynchronousSocketClient("192.168.0.1", 40001, "c:\\log", xml);
socket.StartClient();
socket.Dispose();
}
}
class SynchronousSocketClient : IDisposable
{
private string ip;
private int port;
private object data;
public StreamWriter log;
public event EventHandler Disposed;
public SynchronousSocketClient(string ip, int port, string logfile, object data)
{
this.ip = ip;
this.port = port;
this.data = data;
openLog(logfile);
}
public void openLog(string logfile)
{
log = new StreamWriter(logfile, true);
}
public void Dispose()
{
log.Close();
if (this.Disposed != null)
this.Disposed(this, EventArgs.Empty);
}
// Convert an object to a byte array
private byte[] Serialize(object obj)
{
Stream stream = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(stream, obj);
byte[] b = null;
b = new byte[stream.Length];
stream.Position = 0;
stream.Read(b, 0, (int)stream.Length);
stream.Close();
return b;
}
public void StartClient()
{
// Data buffer for incoming data.
byte[] bytes = new byte[1024];
// Connect to a remote device.
try {
// Establish the remote endpoint for the socket.
// This example uses port 11000 on the local computer.
IPHostEntry ipHostInfo = Dns.GetHostEntry(ip);
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress,port);
// Create a TCP/IP socket.
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp );
// Connect the socket to the remote endpoint. Catch any errors.
try {
sender.Connect(remoteEP);
log.WriteLine(DateTime.Now+": Socket connected to {0}",
sender.RemoteEndPoint.ToString());
// Encode the data string into a byte array.
byte[] msg = Serialize(data);
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
log.WriteLine(DateTime.Now + ": {0}",
Encoding.Unicode.GetString(bytes,0,bytesRec));
// Release the socket.
sender.Shutdown(SocketShutdown.Both);
sender.Close();
} catch (ArgumentNullException ane) {
log.WriteLine(DateTime.Now + ": ArgumentNullException : {0}", ane.ToString());
} catch (SocketException se) {
log.WriteLine(DateTime.Now + ": SocketException : {0}", se.ToString());
} catch (Exception e) {
log.WriteLine(DateTime.Now + ": Unexpected exception : {0}", e.ToString());
}
} catch (Exception e) {
log.WriteLine(DateTime.Now+": "+e.ToString());
}
}
}
//SERVER:
class ProgramServer
{
static void Main(string[] args)
{
NetworkSocket socket = new NetworkSocket(nwsocketport);
socket.Start();
}
}
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of send buffer.
public const int sBufferSize = 1024;
// send buffer.
public byte[] sBuffer = new byte[sBufferSize];
// Received data object;
public object data = null;
// bytes read so far
public int bytesRead;
//receive buffer
public byte[] rBuffer;
}
public class NetworkSocket
{
private int port;
Socket listener;
IPEndPoint localEndPoint;
public NetworkSocket(int port) {
this.port = port;
}
public void Start() {
// Establish the local endpoint for the socket.
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[1];
localEndPoint = new IPEndPoint(ipAddress, port);
// Create a TCP/IP socket.
listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp );
//set socket timeouts
listener.SendTimeout = 5000;
listener.ReceiveTimeout = 5000;
// Bind the socket to the local endpoint and listen for incoming connections.
try {
listener.Bind(localEndPoint);
listener.Listen(1);
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
public 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);
// Create the state object.
StateObject state = new StateObject();
// Data buffer for incoming data.
state.rBuffer = new Byte[listener.ReceiveBufferSize];
state.workSocket = handler;
handler.BeginReceive(state.rBuffer, 0, state.rBuffer.Length, 0,
new AsyncCallback(ReadCallback), state);
try
{
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public void ReadCallback(IAsyncResult ar) {
// Retrieve the state object and the handler socket
// from the asynchronous state object.
StateObject state = (StateObject) ar.AsyncState;
Socket handler = state.workSocket;
//handler.ReceiveTimeout = 2000;
// Read data from the client socket.
state.bytesRead = handler.EndReceive(ar);
Send(handler, "paket successfully tranferred");
state.data = Deserialize(state.rBuffer);
bool xmlDoc = true;
try
{
XDocument.Parse(state.data.ToString());
}
catch
{
xmlDoc = false;
}
if (xmlDoc)
XMLHandler.update(state.data.ToString());
}
private void Send(Socket handler, String data) {
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.Unicode.GetBytes(data);
// Begin sending the data to the remote device.
handler.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), handler);
}
private void SendCallback(IAsyncResult ar) {
try {
// Retrieve the socket from the state object.
Socket handler = (Socket) ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = handler.EndSend(ar);
Console.WriteLine("Sent {0} bytes to client.", bytesSent);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
// Convert a byte array to an Object
private object Deserialize(byte[] b)
{
MemoryStream stream = new MemoryStream(b);
BinaryFormatter bf = new BinaryFormatter();
object obj = bf.Deserialize(stream);
stream.Close();
return obj;
}
// convert object to byte array
private byte[] Serialize(object obj)
{
Stream stream = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(stream, obj);
byte[] b = null;
b = new byte[stream.Length];
stream.Position = 0;
stream.Read(b, 0, (int)stream.Length);
stream.Close();
return b;
}
}
Could anybody please help me with my problem? I am not experienced in Socket Programming...
In your ReadCallback you need to start another BeginReceive, just like how you call BeginAccept in the AcceptCallback method.
A more serious issue with your code is that you expect to receive one entire message per ReadCallback. In reality, you could receive half a message, one byte, or three messages.

Categories

Resources