How to create new ServerSocket C# - c#

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace PowerCarsMobileServer
{
class Server
{
public static int Port { get; private set; }
private static TcpListener tcpListener;
public static ServerSocket serverSocket; //problem is here
public static void Start(int _port)
{
Port = _port;
serverSocket = new ServerSocket(Port);
Console.WriteLine("Starting server...");
InitializeServerData();
tcpListener = new TcpListener(IPAddress.Any, Port);
tcpListener.Start();
Console.WriteLine($"Server started on {Port}.");
}
}
}
When creating a global port, I ran into the problem of not supporting "ServerSocket". Older articles use ServerSocket but I don't understand the problem comparing my code with theirs.
How can I fix it?
I tried to connect different references, but it doesn't work or I didn't find a good one

Related

Why doesn't my udp client throw an exception when I try to receive data in the method RecData()?

It's for a multiplayer video game:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
namespace ShootingMasters
{
public class Communicator
{
public UdpClient client;
public IPAddress toconnectto;
public Communicator(IPAddress toconnectto)
{
this.toconnectto = toconnectto;
client = new UdpClient();
client.Connect(toconnectto, 25565);
}
public void SendData(string data)
{
byte[] bdata = ASCIIEncoding.ASCII.GetBytes(data);
IPEndPoint iP = new IPEndPoint(toconnectto, 25565);
try
{
client.Send(bdata, bdata.Length);
}
catch(Exception e)
{
}
}
public string RecData()
{
if (client.Available > 0)
{
try
{
IPEndPoint iPEndPoint = new IPEndPoint(IPAddress.Any, 25565);
byte[] data = client.Receive(ref iPEndPoint);
return ASCIIEncoding.ASCII.GetString(data);
}
catch(Exception e)
{
return null;
}
}
else
{
return null;
}
}
}
}
When you call receive, it returns null because an exception was thrown. The exception message was
An existing connection was forcibly closed by the remote host
Also, inside receive client.Available is 1 then right after an exception is thrown, it is 0.

Multithreaded network application issues

I've looked at least a hundred threads and none gave me a solution to my specific problem so far and i got tired of looking,
I'm trying to emulate a runescape game server in C#,
I need to receive lots of connections and parse the requests and send out responses for them until the game has loaded all the files, and then proceed to the actual login protocol. this needs to be able to handle multiple connections per second, as in, i handle 3 basic protocols "jaggrab", "ondemand" and then regular game protocol i.e; login, player updating etc these are all handled on the same port
My Server class listens for connections on one thread, while on another thread my PipelineFactory handles the connections in a Queue one by one as fast as it can, meanwhile there is a TaskPool thread which is executing PoolableTask objects at their own individual intervals... this works fine except as soon as I accept a connection both the pool and server threads begin to block and furthermore, the server object stops listening for connections all together but the thread seems to keep running.. I assume this is because the TcpListener.Pending() is not being updated? but i cant seem to find a function to update this list in the docs or anywhere
I seem to be using the threads the way all the multithreading tutorials explain them to work? i dont really understand what im doing wrong.. heres the important parts of my code:
MainEntry.cs:
using System;
using System.Threading;
using gameserver.evt;
using gameserver.io;
using gameserver;
using gameserver.io.player;
public static class MainEntry
{
public static void Main(string[] args)
{
Console.WriteLine("Starting game server...");
new Thread(new ThreadStart(Server.Run)).Start();
new Thread(new ThreadStart(TaskPool.Run)).Start();
new Thread(new ThreadStart(PipelineFactory.Run)).Start();
//TODO maybe pool these
}
}
Server.cs:
using gameserver.io.player;
using gameserver.io.sql;
using gameserver.model;
using gameserver.model.player;
using util;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using gameserver.io.player.pipeline;
using gameserver.evt;
using util.cache;
namespace gameserver.io
{
public class Server
{
public static TcpListener serverSocket;
public static Dictionary<int, Player> players = new Dictionary<int, Player>(Constants.MaxPlayers);
public static Database database;
public const int ListenPort = 43594;
public static bool running = true;
public static readonly Cache cache = new Cache(Constants.CacheDir);
public static void Bind()
{
serverSocket = new TcpListener(IPAddress.Parse("0.0.0.0"), ListenPort);
serverSocket.Start();
Console.WriteLine("Server started at 0.0.0.0:" + ListenPort);
}
public static void Run()
{
if (serverSocket == null)
Bind();
while(IsRunning())
{
Console.Write("serve");
var incoming = serverSocket.AcceptTcpClient();
if (incoming != null)
{
PipelineFactory.queue.Enqueue(new PlayerSocket(incoming));
}
Thread.Sleep(25);
}
}
private static void Destroy()
{
serverSocket.Stop();
//saveall players
//Environment.Exit(0);
}
public static bool Online(Player player)
{
if(player == null)
{
return false;
}
for (int i = 0; i < players.Count; i++)
{
if (player.username == players[i].username)
{
return true;
}
}
return false;
}
public static Database Database => database ?? (database = new Database());
public static bool IsRunning() => running;
}
}
TickPool.cs:
using gameserver.io;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace gameserver.evt
{
public class TaskPool
{
public static bool running = true;
public static List<PoolableTask> tasks = new List<PoolableTask>();
public static void Run()
{
do
{
long cur = Environment.TickCount;
Console.Write("tick");
foreach (PoolableTask t in tasks)
{
if (cur - t.last >= t.interval)
{
if (t == null)
continue;
t.Execute();
t.last = cur;
}
}
Thread.Sleep(100);
} while (Server.IsRunning());
}
public static void Add(PoolableTask task)
{
if(!tasks.Contains(task))
tasks.Add(task);
}
public static void Stop(PoolableTask task)
{
if(tasks.Contains(task))
tasks.Remove(task);
}
}
}
PipelineFactory.cs:
using gameserver.evt;
using gameserver.io.player.pipeline;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace gameserver.io.player
{
// simple but effective state machine for all non player model related protocol
public class PipelineFactory
{
public static Queue<PlayerSocket> queue = new Queue<PlayerSocket>(100);
private static readonly LoginPipe loginPipe = new LoginPipe();
private static readonly JaggrabPipe jgpipe = new JaggrabPipe();
private static readonly HandshakePipe handshake = new HandshakePipe();
private static readonly OnDemandPipe ondemand = new OnDemandPipe();
public static void Run()
{
while (Server.IsRunning())
{
Console.Write("pipe");
if (queue.Count() > 0)
{
var socket = queue.First();
if (socket == null || !socket.GetSocket().Connected
|| socket.state == PipeState.Play)
{
queue.Dequeue();
return;
}
switch (socket.state)
{
case PipeState.Handshake:
socket.currentPipeline = handshake;
break;
case PipeState.Jaggrab:
socket.currentPipeline = jgpipe;
break;
case PipeState.OnDemand:
socket.currentPipeline = ondemand;
break;
case PipeState.LoginResponse:
case PipeState.Block:
case PipeState.Finalize:
socket.currentPipeline = loginPipe;
break;
case PipeState.Disconnect:
//TODO: Database.saveForPlayer
socket.Close();
break;
}
try
{
if (socket.currentPipeline != null)
socket.state = socket.currentPipeline.HandleSocket(socket);
}
catch (Exception)
{
socket.Close();
queue.Dequeue();
}
}
Thread.Sleep(20);
}
}
}
}
The protocol itself really shouldn't matter just know it's all being handled asynchronously
I'm a java programmer at heart but trying to delve into C# head first so thats why my conventions might not be perfect, and I don't really know how to/dont understand intellisense documentation but at some point ill look into it
EDIT: I just wanna note that everything worked perfectly before i tried using threads to multithread this, when i had the PipelineFactory a PoolableTask object implementation, it could handle multiple connections etc and there was only the main thread calling 2 while loops handling everything in the whole server, i'm trying to spread out the load over the cpu but its not working out for me lol

WiFi communication between C# and ESP8266 [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I'm working on school project right now and I'm looking for the simplest way to connect C# with ESP8266 not via SerialPort (COM4) but via WiFi module on ESP8266 (I have to use this method). I have to build simple project to sending measured data from ESP to C# and also receiving my own defined control commands (strings like "LEDON" "LEDOFF" etc.) from C# to ESP just like remote control of measurement project. I have low knowledge in C# same as basics of servers/internet and things like that. I have everything done in Arduino IDE code but I'm stuck on C# cause I never before programmed there. I hope you understand my bad English and concept of my question. :)
EDIT:
Well, so I did some changes in my school project and now I am on this stage, where I need to solve this part of code. I hope that is last step to finish my project. All I have to do is solve Writing data from C# to ESP using unfilled method named "Writing" in following code:
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace ESP8266
{
public class Projekt
{
public event MessageEventHandler Message;
public delegate void MessageEventHandler(Projekt sender, string Data);
public TcpListener server;
public Thread W_Thread;
public Thread R_Thread;
public bool IsLiserning = true;
public TcpClient client;
public StreamReader clientdata;
public StreamWriter serverdata;
public Projekt()
{
server = new TcpListener(IPAddress.Parse(Dns.GetHostEntry(Dns.GetHostName().ToString()).AddressList[1].ToString()), 5000);
server.Start();
W_Thread = new Thread(new ThreadStart(Writing));
W_Thread.Start();
R_Thread = new Thread(new ThreadStart(Reading));
R_Thread.Start();
}
public void Reading()
{
while (IsLiserning == true)
{
if (server.Pending() == true)
{
client = server.AcceptTcpClient();
clientdata = new StreamReader(client.GetStream());
}
try
{
Message?.Invoke(this, clientdata.ReadLine());
}
catch (Exception){}
}
}
public void Writing()
{
while (IsLiserning == true)
{
if (server.Pending() == true)
{
client = server.AcceptTcpClient();
serverdata = new StreamWriter(client.GetStream());
}
try
{
//NEED_TO_SOLVE_THIS_PART
}
catch (Exception){}
}
}
}
}
Maybe there is missing something more than that part of code and you guys are able to help me I hope :) Thanks for all answers by the way :)
You may look at this project, basically you want to communicate via TCP/IP between the arduino and the C#. consider the C# as the server and the arduino as the client. Then they just need to send message to each other to communicate.
The link I'm providing is doing a lot more than needed, so if you're lost, maybe start with something really basic and look here and check the links at the end talking about c# server. They will be easier to understand compared to my first link.
[EDIT] Ok, only links answer is dangerous and not the best, so here is a really light version of what I gave through the first link:
Your server will have a list of receivers, each receiver only handle one client. It's a big simplification of one of my project, I hope that by removing lots of things I didn't break anything:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Windows.Data;
namespace DemoServer.Models
{
public class Server
{
public TcpListener Listener { get; set; }
public int Port { get; set; }
public bool IsStarted { get; private set; }
public List<Receiver> Receivers = new List<Receiver>();
public Server(int port)
{
Receivers.Clear();
BindingOperations.EnableCollectionSynchronization(Receivers, Receivers);
Port = port;
IsStarted = false;
}
public void Start()
{
if (!IsStarted)
{
try
{
Listener = new TcpListener(System.Net.IPAddress.Any, 0);
Listener.Start();
IsStarted = true;
IPAddress address = ((IPEndPoint)Listener.LocalEndpoint).Address;
int port = ((IPEndPoint) Listener.LocalEndpoint).Port;
Console.WriteLine("Server Started");
//Start Async pattern for accepting new connections
WaitForConnection();
}
catch (Exception e)
{
Console.WriteLine(e);
IsStarted = false;
}
}
}
public void Stop()
{
if (IsStarted)
{
Listener.Stop();
IsStarted = false;
Receivers.Clear();
Console.WriteLine("Server Stopped");
}
}
private void WaitForConnection()
{
Listener.BeginAcceptTcpClient(new AsyncCallback(ConnectionHandler), null);
}
private void ConnectionHandler(IAsyncResult ar)
{
if (IsStarted)
{
Receiver newClient = new Receiver(Listener.EndAcceptTcpClient(ar), this);
newClient.Start();
Receivers.Add(newClient);
WaitForConnection();
}
}
public void SomeInteractionBetweenClients()
{
Console.WriteLine("Interaction!");
}
}
}
Then comes the Receiver code, where you really handle the communication with your client:
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Threading;
namespace DemoServer.Models
{
public class Receiver : ModelBase
{
bool ConnectionStatus = false;
private uint m_Id = 0;
public uint Id
{
get { return m_Id; }
set => SetAndRaisePropertyChanged(ref m_Id, value);
}
private Thread receivingThread;
private Thread sendingThread;
public Server Server { get; set; }
public TcpClient Client { get; set; }
public List<String> MessageQueue { get; private set; }
public Receiver(TcpClient client, Server server)
{
MessageQueue = new List<String>();
Server = server;
Client = client;
Client.ReceiveBufferSize = 1024;
Client.SendBufferSize = 1024;
ConnectionStatus = true;
}
public void Start()
{
receivingThread = new Thread(ReceivingMethod);
receivingThread.IsBackground = true;
receivingThread.Start();
sendingThread = new Thread(SendingMethod);
sendingThread.IsBackground = true;
sendingThread.Start();
}
private void Disconnect()
{
if (!ConnectionStatus) return;
ConnectionStatus = false;
Client.Client.Disconnect(false);
Client.Close();
}
private void SendingMethod()
{
while (ConnectionStatus)
{
if (MessageQueue.Count > 0)
{
var message = MessageQueue[0];
try
{
NetworkStream clientStream = Client.GetStream();
StreamWriter streamWriter = new StreamWriter(clientStream);
streamWriter.Write(message);
streamWriter.Flush();
Console.WriteLine($"We are sending '{message}' to the client");
}
catch
{
Disconnect();
}
finally
{
MessageQueue.RemoveAt(0);
}
}
Thread.Sleep(30);
}
}
private void ReceivingMethod()
{
while (ConnectionStatus)
{
if (Client.Available > 0)
{
try
{
NetworkStream clientStream = Client.GetStream();
StreamReader streamReader = new StreamReader(clientStream);
char[] puchBuffer = new char[Client.Available];
int iQtt = streamReader.Read(puchBuffer, 0, Client.Available);
string msg = String.Empty;
for (int i = 0; i < puchBuffer.Length; i++)
{
msg = $"{msg}{Convert.ToString(puchBuffer[i])}";
}
OnMessageReceived(msg);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
Thread.Sleep(30);
}
}
private void OnMessageReceived(String msg)
{
// Here you can parse the messages coming ffrom the client and do whatever is needed
// If needed, you can even call some public methods from the server to forward some info to an other client for example or just the server:
// eg: Server.SomeInteractionBetweenClients();
}
}
}
I hope this will help for the communication part. For the GUI there are lots of tutorials on the web but if possible I still think WPF/MVVM is better to learn than winforms.
From my understanding your project requires 2 way communication. Making c# as server will not be ideal since there is no easy way to send command from C# to esp8266. I assume your project is utilizing esp8266 as the arduino platform (not attaching esp8266 to arduino as wifi module), please check out MQTT which is a broker for publishing and subscribing messages. That way both esp8266 and C# code and communicate via MQTT and achieve 2 way communication purpose.
for esp8266, you can check out arduino MQTT library for esp8266 here: https://github.com/knolleary/pubsubclient.

Testing UDP Locally C#

I am writing a mono C# application that needs to use UDP. I was writing my test suite so that I could make sure packets are received properly with NUnit.
I made a minimal working example with a UdpCom class that is supposed to just listen right now and print out the bytes it receives in the call back method.
My minimal UdpCom class looks like:
using System;
using System.Net;
using System.Net.Sockets;
namespace UdpPractice
{
public class UdpState
{
public UdpClient client;
public IPEndPoint endpoint;
public UdpState(UdpClient c, IPEndPoint iep)
{
this.client = c;
this.endpoint = iep;
}
}
public class UdpCom
{
public UdpState uState;
public UdpClient uClient;
public IPAddress address;
public int port;
public IPEndPoint uEndpoint;
public UdpCom (IPAddress address, int port)
{
uEndpoint = new IPEndPoint (address, port);
uClient = new UdpClient (uEndpoint);
uState = new UdpState (uClient, uEndpoint);
uClient.BeginReceive (new AsyncCallback(RxCallback), uState);
}
public void RxCallback(IAsyncResult result)
{
UdpState rState = (UdpState)(result.AsyncState);
UdpClient rClient = rState.client;
IPEndPoint rEndPoint = rState.endpoint;
byte[] rxBytes = rClient.EndReceive (result, ref rEndPoint);
Console.WriteLine ("Received Bytes ___________________________");
Console.WriteLine (rxBytes.ToString ());
rClient.BeginReceive (new AsyncCallback(RxCallback), rState);
}
}
}
My simple test instantiates this class and then sends it a dummy packet of bytes. I am not testing the result right now, just placing a break point in my RxCallback method.
This is my NUNIT test:
using NUnit.Framework;
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using UdpPractice;
namespace UdpTest
{
[TestFixture ()]
public class Test
{
[Test ()]
public void TestCase ()
{
// Setup Receiver
IPAddress address = new IPAddress (new byte[] { 127, 0, 0, 1 });
int port = 14580;
UdpCom com = new UdpCom (address, port);
com.uClient.Connect (com.uEndpoint);
// Set up sender
UdpClient sender = new UdpClient(new IPEndPoint (address, port));
sender.Connect (address, port);
// Dummy Data
byte [] dummyData = new byte[] {1, 2, 3, 4, 4, 5};
sender.Send (dummyData, dummyData.Length);
Thread.Sleep (100);
// Close
sender.Close ();
com.uClient.Close ();
}
}
}
My Issue is that when I'm in the RxCallback method on the line that I'm trying to retrieve the bytes I am getting this exception:
System.ObjectDisposedException has been thrown
Cannot access a disposed object.
Object name: System.Net.Sockets.UdpClient
I want to be able to store these bytes in a queue in my UdpCom class but I am having trouble accessing them in the first place.
I may be failing to udner stand some basic UDP concepts as well here but it seems pretty straght forward.
The udp examples I have been following are:
https://yal.cc/cs-dotnet-asynchronous-udp-example/
https://www.codeproject.com/articles/132623/basic-udp-receiver
EDIT
I updated my class and tests as follows so I don't use the local loopback. But I am still getting the same exception.
UdpCom is now:
using System;
using System.Net;
using System.Net.Sockets;
namespace UdpPractice
{
public class UdpState
{
public UdpClient client;
public IPEndPoint endpoint;
public UdpState(UdpClient c, IPEndPoint iep)
{
this.client = c;
this.endpoint = iep;
}
}
public class UdpCom
{
public UdpState uState;
public UdpClient uClient;
public IPAddress address;
public int port;
public IPEndPoint uEndpoint;
public UdpCom (IPAddress address, int port)
{
uEndpoint = new IPEndPoint (address, port);
uClient = new UdpClient (uEndpoint);
uState = new UdpState (uClient, uEndpoint);
uClient.BeginReceive (new AsyncCallback(RxCallback), uState);
}
public void RxCallback(IAsyncResult result)
{
UdpState rState = (UdpState)(result.AsyncState);
UdpClient rClient = rState.client;
IPEndPoint rEndPoint = rState.endpoint;
byte[] rxBytes = rClient.EndReceive (result, ref rEndPoint);
Console.WriteLine ("Received Bytes ___________________________");
Console.WriteLine (rxBytes.ToString ());
rClient.BeginReceive (new AsyncCallback(RxCallback), rState);
}
}
}
and the test is:
using NUnit.Framework;
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using UdpPractice;
namespace UdpTest
{
[TestFixture ()]
public class Test
{
[Test ()]
public void TestCase ()
{
// Setup Receiver
IPAddress address = new IPAddress (new byte[] { 192, 168, 1, 161 });
int port = 14580;
UdpCom com = new UdpCom (IPAddress.Any, port);
// com.uClient.Connect (com.uEndpoint);
// Set up sender
UdpClient sender = new UdpClient(new IPEndPoint (address, port));
sender.Connect (address, port);
// Dummy Data
byte [] dummyData = new byte[] {1, 2, 3, 4, 4, 5};
sender.Send (dummyData, dummyData.Length);
Thread.Sleep (100);
// Close
sender.Close ();
com.uClient.Close ();
}
}
}
I guess I was struggling with a basic misunderstanding with how to communicate with UDP.
UdpCom:
using System;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;
namespace UdpPractice
{
public class UdpState
{
public UdpClient client;
public IPEndPoint endpoint;
public UdpState(UdpClient c, IPEndPoint iep)
{
this.client = c;
this.endpoint = iep;
}
}
public class UdpCom
{
public UdpState uState;
public IPAddress address;
public int port;
public IPEndPoint uEndpoint;
public bool receiveFlag;
public List<byte[]> rxBytesBuffer;
public UdpCom (IPAddress address, int port)
{
uEndpoint = new IPEndPoint (address, port);
// uClient = new UdpClient (uEndpoint);
uState = new UdpState (new UdpClient(new IPEndPoint(IPAddress.Parse("127.0.0.1"), port)), uEndpoint);
receiveFlag = false;
uState.client.BeginReceive (new AsyncCallback(RxCallback), uState);
rxBytesBuffer = new List<byte[]> ();
}
public void RxCallback(IAsyncResult result)
{
UdpState rState = (UdpState)result.AsyncState;
UdpClient rClient = ((UdpState)result.AsyncState).client;
IPEndPoint rEndPoint = ((UdpState)result.AsyncState).endpoint;
byte[] rxBytes = rClient.EndReceive (result, ref rEndPoint);
rxBytesBuffer.Add (rxBytes);
Console.WriteLine ("Received Bytes ___________________________");
Console.WriteLine (rxBytes.ToString ());
receiveFlag = true;
rClient.BeginReceive (new AsyncCallback(RxCallback), result.AsyncState);
}
}
}
Test:
using NUnit.Framework;
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using UdpPractice;
namespace UdpTest
{
[TestFixture ()]
public class Test
{
[Test ()]
public void TestCase ()
{
// Setup Listener
int port = 14580;
IPEndPoint locep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);
// Server (Listener)
UdpCom com = new UdpCom (IPAddress.Any, port);
// Set up sender
UdpClient sender = new UdpClient();
// Dummy Data
byte [] dummyData = new byte[] {1, 2, 3, 4, 4, 5};
sender.Send (dummyData, dummyData.Length, locep);
sender.Send (dummyData, dummyData.Length, locep);
Thread.Sleep (100);
Assert.AreEqual(true, com.receiveFlag);
}
}
}
I needed to make the listener listen to IPAddress.Any and then I mainly used the Send method with the EndPoint argument. I had to add the delay in there because otherwise the receive flag wasn't being set.

Notify UDP-Server via PCo (Plant Connetivity) Agent

I have a problem.
The point is to establish a connection between an SAP server and UDP server (Java application).
These Plant Connectivity should be used.
To this end, I have to write a so-called agent.
Seeking for days from the Internet and have read various documents, but I could not find anything decisive.
using System;
using System.Net.Sockets;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SAP.Manufacturing.Connectivity;
using SAP.Manufacturing.Connectivity.Tracing;
using SAP.Manufacturing.Connectivity.InternalConfig;
using System.Timers;
using System.Diagnostics;
using SAP.Manufacturing.Connectivity.Query.Text;
using SAP.Manufacturing.Connectivity.Query.Response;
namespace TTAgent
{
[Agent(ChannelRetryModel = CommunicationChannelRetryModel.Passive)]
[NotificationSupport]
public partial class Agent : AgentBase
{
UdpClient client;
public Agent() : base() { }
public Agent(AgentInstance instance) : base(instance) { }
public Agent(SourceChannel channel) : base(channel) { }
protected override Aspects GetDefaultSourceChannelConfiguration()
{
Aspects aspects = new Aspects();
Aspect aspect = new Aspect("TrainAgentConfig", "Configuration created at: " + DateTime.Now);
aspects.Add(aspect);
return aspects;
}
protected override void StartInstance(Cache cache)
{
base.StartInstance(cache);
}
protected override void StopInstance() { }
public override void EstablishConnection()
{
client = new UdpClient();
System.Net.IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6767);
client.Connect(endPoint);
}
public override void RevokeConnection(){ }
protected override bool IsConnected()
{
byte[] dgram = new byte[66];
client.Send(dgram, dgram.Length);
return base.IsConnected();
}
new public void Dispose()
{
client.EndSend(null);
client.Close();
}
}
}
I bind the agent in PCo as a source and create an instance, which I start.
But nothing seems to happen.
The current server does not respond
Is there someone who is familiar with SAP and agents?
Here the Server:
package leapmotiongesten;
import java.io.IOException;
import java.net.*;
public class UDPServer
{
public static void main( String[] args ) throws IOException
{
DatagramSocket socket = new DatagramSocket( 6767 );
while ( true )
{
DatagramPacket packet = new DatagramPacket( new byte[1024], 1024 );
socket.receive( packet );
InetAddress address = packet.getAddress();
int port = packet.getPort();
int len = packet.getLength();
byte[] data = packet.getData();
System.out.printf( "Anfrage von %s vom Port %d mit der Länge %d:%n%s%n",
address, port, len, new String( data, 0, len ) );
}
}
}

Categories

Resources