Files
AccelVisualizer/ClientTest/Program.cs
2018-04-11 23:08:18 +02:00

83 lines
2.6 KiB
C#

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[512];
// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
// This example uses port 5000 on the local computer.
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = IPAddress.Parse("192.168.0.109");
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 5000);
// Create a TCP/IP socket.
Socket sender = new Socket(ipAddress.AddressFamily,
SocketType.Dgram, ProtocolType.Udp);
// 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.SendTo(msg, remoteEP);
// Creates an IPEndPoint to capture the identity of the sending host.
IPEndPoint sendingEndpoint = new IPEndPoint(IPAddress.Any, 0);
EndPoint senderRemote = (EndPoint)sendingEndpoint;
// Receive the response from the remote device.
while(true)
{
int bytesRec = sender.ReceiveFrom(bytes, ref senderRemote);
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;
}
}