Socket between C# server and C# client - c#

I'm going to create a socket to send a string from console application server to AndroidWearable client. I use Visual Studio Xamarin, and I never use XML Language. When I click the button nothing happens, How can I improve my program?
Part MainActivity.cs
using Android.App;
using Android.OS;
using Android.Support.Wearable.Activity;
using Android.Views;
using Android.Widget;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace AndroidClient
{
[Activity(Label = "#string/app_name", MainLauncher = true)]
public class MainActivity : WearableActivity
{
private TextView textView;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.activity_main);
textView = FindViewById<TextView>(Resource.Id.text);
SetAmbientEnabled();
}
/** Called when the user touches the button */
// 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.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(ipAddress.AddressFamily,
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();
data = null;
// An incoming connection needs to be processed.
while (true)
{
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("<EOF>") > -1)
{
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 void mainsendMessage(View view)
{
// Do something in response to button click
StartListening();
}
}
}
Part AXML-Origin
<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/button_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send"
android:onClick="sendMessage" />
Server C#
SERVER
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace Server_microsoft
{
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.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(ipAddress.AddressFamily,
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();
data = null;
// An incoming connection needs to be processed.
while (true)
{
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf(data) > -1)
{
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 int Main(String[] args)
{
StartListening();
return 0;
}
}
}
Thanks!
For example I have to inser some TextView o see the string? How can I make this or one button is necessary?

Related

No connection could be made because the target machine active refused it?

My problem is weird and i was not able to find a resolution from referring to other threads regarding this. I am getting the error when i run the microsoft Synchronous Server Socket Example, Synchronous Client Socket Example, on two systems which are part of the domain but i do not get this error when i run the same code on two systems which are part of the network but they are not part of the domain! Anyone know what might be causing the issue?
The things i have done to try to resolve are I made sure the port was open, switched off the firewall and antivirus as suggested by others with similar problem.But it has not helped.
Server code:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
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.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(ipAddress.AddressFamily,
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();
data = null;
// An incoming connection needs to be processed.
while (true) {
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes,0,bytesRec);
if (data.IndexOf("<EOF>") > -1) {
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 int Main(String[] args) {
StartListening();
return 0;
}
}
Client Code::
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.
IPAddress ipAddress = IPAddress.Parse("172.21.98.122");//Server IP
IPEndPoint remoteEP = new IPEndPoint(ipAddress,11000);
// Create a TCP/IP socket.
Socket sender = new Socket(ipAddress.AddressFamily,
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.
byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");
// 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();
return 0;
}
}

Trying to Connect RPI to Unity via TCP

I am working on a small project and I am at the point where I want to connect my Raspberry Pi to Unity (running on my PC). I am able to make a connection running Visual Studio, but when I run the same code in Unity, no connections happen.
C# Code
using System;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
// State object for reading client data asynchronously
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.GetHostEntry(Dns.GetHostName());
//IPAddress ipAddress = Array.Find(ipHostInfo.AddressList, x => x.AddressFamily == AddressFamily.InterNetwork);
IPAddress ipAddress = IPAddress.Any;
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 6670);
Console.WriteLine($"Connected on {localEndPoint}");
// Create a TCP/IP socket.
Socket listener = new Socket(ipAddress.AddressFamily,
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.
Console.WriteLine("Waiting for a connection...");
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener );
Console.WriteLine("Accepted");
// Wait until a connection is made before continuing.
allDone.WaitOne();
Console.WriteLine("After wait");
}
} catch (Exception e) {
Console.WriteLine(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);
// 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.
var stringRead = Encoding.ASCII.GetString(
state.buffer, 0, bytesRead);
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.
Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
content.Length, content );
// Echo the data back to the client.
Send(handler, content);
} else {
string timestamp = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff",
CultureInfo.InvariantCulture);
Console.WriteLine(timestamp + ": " + stringRead);
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
//Test Code
Send(handler, "boogieboogie");
}
}
}
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);
Console.WriteLine("Sent {0} bytes to client.", bytesSent);
//handler.Shutdown(SocketShutdown.Both);
//handler.Close();
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
public static int Main(String[] args) {
Thread t = new Thread(StartListening);
t.Start();
//FingerMovement.Service();
return 0;
}
}
The Python code is just doing a socket connect to the IP and port.
So to restate the question: Why does it not connect to the RPI when I run this in Unity? No connections occur, however, if I run the same exact code through VS, it connects just fine.
I allowed Unity in my firewall, tried running it in Admin, still nothing.
It's a bit of a long shot but have you enabled 'run in the background' checkbox in the player settings? I've had unity miss a whole lot of system events / transmissions while I was switching windows when this was off. I think all the child processes freeze when Unity looses focus by default, and I think that inclueds the async quasi-processes, or at the very least it surely includes your main thread which communicates with you

.net sockets data transmition using sockets (c#)

I'm trying to transfer some data between android client and .net server.
I used sockets. the client sockets is connected while in the server I get no response.
can anyone please review this code and help me? I'm kind of lost.
my client code:
Socket socket1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
try
{
socket1.Connect(IPAddress.Parse(string_ip), 8080);
if (socket1.Connected)
{
Log("connected");
NetworkStream networkStream1 = new NetworkStream(socket1);
byte[] sendData = new byte[1024];
byte[] recievedData = new byte[1024];
string message = "alon aviv";
sendData = Encoding.UTF8.GetBytes(message);
networkStream1.Write(sendData, 0, sendData.Length);
}
else
{ Log("not connected"); }
}
my server code:
Socket socket1 = new Socket(SocketType.Stream, ProtocolType.IP);
System.Net.IPEndPoint ipEnd = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(string_ip), 8080);
socket1.Bind(ipEnd);
socket1.Listen(1);
socket1.Accept();
if (socket1.Connected)
{
UpdateLogText("socket connected");
NetworkStream networkStream1 = new NetworkStream(socket1);
byte[] recievedData = new byte[1024];
networkStream1.Read(recievedData, 0, recievedData.Length);
string message_recieved = Encoding.ASCII.GetString(recievedData);
UpdateLogText(message_recieved);
}
I also tested your code and it was not working at my side as well. I made some adjustments which do work. Please try:
Client
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
byte[] bytes = new byte[1024];
Socket socket1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
try
{
socket1.Connect(IPAddress.Parse("127.0.0.1"), 8080);
if (socket1.Connected)
{
Console.WriteLine("Connected");
// Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");
// Send the data through the socket.
int bytesSent = socket1.Send(msg);
// Receive the response from the remote device.
int bytesRec = socket1.Receive(bytes);
Console.WriteLine("Echoed test = {0}",
Encoding.ASCII.GetString(bytes, 0, bytesRec));
// Release the socket.
socket1.Shutdown(SocketShutdown.Both);
socket1.Close();
}
else
{
Console.WriteLine("not connected");
}
Console.ReadLine();
}
catch (Exception e)
{
}
}
}
}
Server
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
public static string data = null;
static void Main(string[] args)
{
byte[] bytes = new Byte[1024];
Socket socket1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
System.Net.IPEndPoint ipEnd = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"), 8080);
// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
socket1.Bind(ipEnd);
socket1.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 = socket1.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.IndexOf("<EOF>") > -1)
{
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.ReadLine();
}
}
}

get variable from infinite loop in .net socket

I'm using .NET synchronous socket to send data from a client to server.
I need to get the data from the StartListening() method to use it in the Main() but
the variable data is inside an infinite loop ( while(true)).
Any help please?
This is the server code :
using System;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SynchronousSocketListener
{
byte[] bytes = new Byte[1024];
IPHostEntry ipHostInfo;
IPAddress ipAddress ;
IPEndPoint localEndPoint;
Socket listener;
// Incoming data from the client.
public static string data = null;
// Volatile is used as hint to the compiler that this data
// member will be accessed by multiple threads.
private volatile bool _shouldStop;
public void InitializeListening()
{
// Data buffer for incoming data.
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
ipHostInfo = Dns.Resolve("localhost");
ipAddress = ipHostInfo.AddressList[0];
localEndPoint = new IPEndPoint(ipAddress, 11007);
// Create a TCP/IP socket.
listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(localEndPoint);
listener.Listen(10);
}
public void StopListening()
{
_shouldStop = true;
byte[] msg = Encoding.ASCII.GetBytes("please stop!");
// 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(localEndPoint);
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// 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());
}
}
public void StartListening()
{
// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
// Start listening for connections.
while (true)
{
Console.WriteLine("Waiting for a connection...");
// Thread is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
// An incoming connection needs to be processed.
if (_shouldStop)
{
handler.Shutdown(SocketShutdown.Both);
handler.Close();
break;
}
data = null;
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("<EOF>") > -1)
{
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);
byte[] msg = Encoding.ASCII.GetBytes("Salam !");
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static int Main(String[] args)
{
Console.WriteLine("I am the Synchronous Socket Server\n");
SynchronousSocketListener pServer = new SynchronousSocketListener();
pServer.InitializeListening();
Thread serverkerThread = new Thread(pServer.StartListening);
serverkerThread.Start();
// Loop until server thread activates.
while (!serverkerThread.IsAlive) ;
Console.WriteLine("listening thread sevice started...\n");
Console.WriteLine("\nPress Q when you want to quit...\n");
int car;
do
{
Thread.Sleep(100);
car = Console.Read();
if (car == 81)
{
// Request that the worker thread stop itself:
pServer.StopListening();
// Use the Join method to block the current process
// until the object's thread terminates.
serverkerThread.Join();
break;
}
} while (true);
Console.WriteLine("listening thread sevice stopped and program will be exited...\n");
return 0;
}
}
The received data (given it is an ASCII-string ending with "EOF") is stored in the public member named "data" of your pServer object, you can access it like this:
Thread serverkerThread = new Thread(pServer.StartListening);
serverkerThread.Start();
// Loop until server thread activates.
while (!serverkerThread.IsAlive) ;
string receivedString = pServer.data; // <<--- here we get the received string
Console.WriteLine("listening thread sevice started...\n");

Asynchronous Server Socket Example

I found this code of Asynchronous Server Socket Example and i am trying to get the data out from the thread where i receive info to update a textbox, but i can't just use a simple string. I've tried something called Control.Invoke Method (Delegate, Object[]) to update it but when the program gets to the form1.Invoke(form1.updateTextBox, content); i get this error:
Invoke or BeginInvoke cannot be called on a control until the window handle has been created.
The sad part is the MessageBox is working and displays the data I receive.
Here is the code:
using System;
using System.Collections.Generic;
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.Threading;
namespace Stream_Socket_Listener {
public partial class Form1 : Form
{
public delegate void updateTextBoxDelegate(String textBoxString); // delegate
public updateTextBoxDelegate updateTextBox;
void updateTextBox1(string str)
{
textBox1.Text = str;
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) { }
private void button1_Click(object sender, EventArgs e)
{
updateTextBox = new updateTextBoxDelegate(updateTextBox1);
AsynchronousSocketListener.StartListening();
}
}
// State object for reading client data asynchronously
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 = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"),
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(100);
while (true)
{
// Set the event to nonsignaled state.
allDone.Reset();
// Start an asynchronous socket to listen for connections.
Console.WriteLine("Waiting for a connection...");
listener.BeginAccept(new AsyncCallback(AcceptCallback),listener);
// Wait until a connection is made before continuing.
allDone.WaitOne();
}
}
catch (Exception e)
{
Console.WriteLine(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);
// 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("Read " + content.Length + " bytes from socket. \n >Data" + content);
Form1 form1 = new Form1();
Application.DoEvents();
form1.Invoke(form1.updateTextBox, 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("Sent "+ bytesSent+ " bytes to client.");
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
I think your problem is because you are invoking the form's method before the form is fully created. Try creating the form beforehand and ignore those calls until the form is ready. Additionally, you might need to do something like this:
if (InvokeRequired)
{
Invoke(new MethodInvoker(addMsg));
}
else
{
updateTextBox(content)
}
To avoid issues due to invoke a method from a different thread.

Categories