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 ) );
}
}
}
Related
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.
Server Code
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Runtime.Serialization.Formatters.Binary;
using Global;
using System.IO;
namespace Server
{
class Program
{
static List<string> BlackList = new List<string>();
static List<TcpClient> Clients = new List<TcpClient>();
static object _lock = new object();
static BinaryFormatter Formatter = new BinaryFormatter();
static TcpListener Server;
static void Main(string[] args)
{
Init();
Console.ReadLine();
}
/*
* Initiate the server and start listening
*/
static void Init()
{
Server = new TcpListener(IPAddress.Any, 7777);
Server.Start();
Task.Factory.StartNew(() => Listen());
}
/*
* Listens to new incoming connections
* Assigns the new client a worker who will listen to it's requests
* Add the client to the list of active clients
*/
static void Listen()
{
for (;;)
{
TcpClient client = Server.AcceptTcpClient();
lock(_lock)
Clients.Add(client);
Task.Factory.StartNew(() => Work(client));
Thread.Sleep(100);
}
}
/*
* Listens to incoming requests from a client and sends a response back if necessary
* On disconnect remove client from active clients list
*/
static void Work(TcpClient client)
{
while (client.Connected)
{
NetworkStream stream = client.GetStream();
try
{
dynamic request = Formatter.Deserialize(stream);
Response response = HandleRequest(request);
if(response != null)
Formatter.Serialize(stream, response);
}
catch(Exception ex)
{
Console.Write(ex.Message);
}
}
lock (_lock)
Clients.Remove(client);
}
/*
* Handles File Transfer Requests
*/
static Response HandleRequest(FileTransferRequest request)
{
string file = request.File;
FileTransferResponse response;
if (File.Exists($"{Environment.CurrentDirectory}\\{file}"))
response = new FileTransferResponse(File.ReadAllBytes(file));
else
response = new FileTransferResponse(null);
return response;
}
}
}
Client Code
using System;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using Global;
using System.IO;
namespace Client
{
class Program
{
static TcpClient Server;
static void Main(string[] args)
{
string file = args[0];
string output = args[1];
Init();
NetworkStream stream = Server.GetStream();
BinaryFormatter formatter = new BinaryFormatter();
//Request
FileTransferRequest request = new FileTransferRequest(file);
formatter.Serialize(stream, request);
//Get Response
FileTransferResponse response = (FileTransferResponse) formatter.Deserialize(stream);
if (response.File == null)
Console.Write("File not found");
else
{
File.WriteAllBytes(output, response.File);
Console.Write("Success");
}
Console.ReadLine();
}
static void Init()
{
try
{
Server = new TcpClient("lordfrostbyte.webhop.me", 7777);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
Environment.Exit(-1);
}
}
}
}
Global Library Code
namespace Global
{
[Serializable]
public abstract class Request
{
}
[Serializable]
public class FileTransferRequest : Request
{
public string File;
public FileTransferRequest(string File)
{
this.File = File;
}
}
[Serializable]
public abstract class Response
{
}
[Serializable]
public class FileTransferResponse : Response
{
public byte[] File;
public FileTransferResponse(byte[] File)
{
this.File = File;
}
}
}
This is my code... It's not working !
But I have configured port forwarding
I have also disabled my firewall
My guess is something is wrong with windows. However I do not want to format my computer in order to solve this. I would much appreciate any input that would lead to solving this issue. I have had this issue for a while and I was wondering if anyone else has had a similar issue and if anyone has ever solved this. At the moment I have no clue how to even troubleshoot this issue. Do note that if I host the server on LAN and connect to LAN it works perfectly.
I had to reinstall pcap drivers.
i am using those scripts bellow to send and receive data, when i send data from an android support to my computer i can't receive anything !!! i can't find the problem can anyone help me please
using UnityEngine;
using System.Collections;
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
public class UDPSend : MonoBehaviour
{
public string IP = "myIP"; // default local
public int port = 26000;
IPEndPoint remoteEndPoint;
UdpClient client;
string strMessage="";
public void Start()
{
init();
}
void OnGUI()
{
Rect rectObj=new Rect(40,380,200,400);
GUIStyle style = new GUIStyle();
style.alignment = TextAnchor.UpperLeft;
GUI.Box(rectObj,"UDPSendData\n IP : "+IP+" Port : "+port,style);
//
strMessage=GUI.TextField(new Rect(40,420,140,20),strMessage);
if (GUI.Button(new Rect(190,420,40,20),"Send"))
{
sendString(strMessage+"\n");
}
}
// init
public void init()
{
IP="myIP";
port=26000; // quake port ;)
remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), port);
//remoteEndPoint = new IPEndPoint(IPAddress.Broadcast, port); // toute machine
client = new UdpClient();
}
// sendData
private void sendString(string message)
{
try
{
byte[] data = Encoding.UTF8.GetBytes(message);
client.Send(data, data.Length, remoteEndPoint);
}
catch (Exception err)
{
print(err.ToString());
}
}
void OnDisable()
{
if ( client!= null) client.Close();
}
}
UDPReceive:
using UnityEngine;
using System.Collections;
using System;
using System.Net;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net.NetworkInformation;
public class UDPReceive : MonoBehaviour {
Thread receiveThread;
UdpClient client;
public int port = 26000;
string strReceiveUDP="";
string LocalIP = String.Empty;
string hostname;
public void Start()
{
Application.runInBackground = true;
init();
}
// init
private void init()
{
receiveThread = new Thread( new ThreadStart(ReceiveData));
receiveThread.IsBackground = true;
receiveThread.Start();
hostname = Dns.GetHostName();
IPAddress[] ips = Dns.GetHostAddresses(hostname);
if (ips.Length > 0)
{
LocalIP = ips[0].ToString();
}
}
void OnGUI()
{
Rect rectObj=new Rect(10,10,400,200);
GUIStyle style = new GUIStyle();
style.alignment = TextAnchor.UpperLeft;
GUI.Box(rectObj,hostname+" MY IP : "+LocalIP+" : "+strReceiveUDP,style);
}
private void ReceiveData()
{
client = new UdpClient(port);
while (true)
{
try
{
IPEndPoint anyIP = new IPEndPoint(IPAddress.Broadcast, port);
//IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
byte[] data = client.Receive(ref anyIP);
string text = Encoding.UTF8.GetString(data);
strReceiveUDP = text;
//Debug.Log(strReceiveUDP);
}
catch (Exception err)
{
print(err.ToString());
}
}
}
public string UDPGetPacket()
{
return strReceiveUDP;
}
void OnDisable()
{
if ( receiveThread!= null) receiveThread.Abort();
client.Close();
}
}
When myIP is 127.0.0.1 everything works normally
I wrote this C# code to have namedPipeServer and NamedPipeClient, with Asynchronous read and write settings, connect to each other. Both code runs perfectly on visual studio 2010 that I am using with read and write working well without any application freeze during runtime.
But I want the client side running in unity3d. The problem I encounter is in client side code implemented in Unity3D. When I use Write_to_Server_Async(string message), read in the server side is not invoked and is only invoked when I quit Unity3d (I have end its process typically). I can tell something wrong with Unity3D, because the exact code works perfectly in visual studio, so I know my code is implemented the right way. I have heard about how unity3d does not really use real threads unless user manually creates one but even that has not solved the problem. My speculation is Unity3D developers might have created their version of .NET library 3.5 (sounds bizzare (does explain why they still haven't adopted 4.5)) or somehow they must have structured their library in a way that by default functions like NamedPipeClientStream.BeginWrite cannot create its own real thread. But then again I am not sure if its the problem with threads.
At the moment, I would like anyone to come up with good explanation.
Make sure to replace Debug.WriteLine to UnityEngine.Debug.Log in unity3d.
Below is Client Main method code and class
class PipeClient
{
private static Asynchronus_NamedPipe_Client client;
static void Main(string[] args)
{
client = new Asynchronus_NamedPipe_Client("mypipe7055");
while (client.Is_connected_to_server()) {
if (Console.ReadKey().Key == ConsoleKey.T)
{
client.Write_to_Server_Async("NEX CLIENT");
}
}
}
}
Asynchronus_NamedPipe_Client class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System;
using System.IO;
using System.IO.Pipes;
using System.Text;
using System.Security.Principal;
using System.Diagnostics;
using System.Threading;
namespace NamedPipes_CLIENT
{
public class Asynchronus_NamedPipe_Client
{
public readonly string pipe_address;
private System.IO.Pipes.NamedPipeClientStream clientStream;
public bool filter_message = true;
private string Server_Message = null;
public event ASYNC_pipe_status_callback ASYNC_external_Write_Completed;
public event ASYNC_pipe_status_callback ASYNC_external_Read_Completed;
public delegate void ASYNC_pipe_status_callback(string message);
private byte[] read_buffer = new byte[1024];
private byte[] write_buffer = new byte[1024];
private IAsyncResult read_result;
private IAsyncResult write_result;
private int read_id = 1;
public Asynchronus_NamedPipe_Client(string pipe_address)
{
try
{
this.pipe_address = pipe_address;
// if(clientStream.IsConnected){UnityEngine.Debug.Log("Server Already Running");}else{}
clientStream = new NamedPipeClientStream(".", this.pipe_address, PipeDirection.InOut, PipeOptions.Asynchronous);
clientStream.Connect(1);
if (clientStream.IsConnected)
{
Console.WriteLine("Connected to Server");
Read_from_Server_Async();
}
else { Console.WriteLine("Could NOT connect to Server"); }
}
catch (Exception oEX) { Console.WriteLine("Application Pipe Error: "+oEX.Message); }
}
public void Write_to_Server_Async(string message)
{
if (clientStream != null)
{
if (clientStream.CanWrite && clientStream.IsConnected)
{
clientStream.WaitForPipeDrain();
ASCIIEncoding.ASCII.GetBytes(message).CopyTo(write_buffer,0);
clientStream.BeginWrite(write_buffer, 0, write_buffer.Length, new AsyncCallback(Async_Write_Completed), 1);
} else { close_pipe(); }
}
}
public void Read_from_Server_Async()
{
if (clientStream.CanRead && clientStream.IsConnected)
{
clientStream.BeginRead(read_buffer, 0, read_buffer.Length, new AsyncCallback(Async_Read_Completed), 2);
} else { close_pipe(); }
}
private void Async_Write_Completed(IAsyncResult result)
{
clientStream.EndWrite(result);
Debug.WriteLine("Written To Server => " + ASCIIEncoding.ASCII.GetString(write_buffer));
// close_pipe();
}
private void Async_Read_Completed(IAsyncResult result)
{
clientStream.EndRead(result);
Server_Message = ASCIIEncoding.ASCII.GetString(read_buffer);
this.Server_Message.Trim();
Console.WriteLine("Received from Server => " + Server_Message);
Debug.WriteLine("Received from Server => " + Server_Message);
if (clientStream.CanRead && clientStream.IsConnected)
{
Read_from_Server_Async();
}
else { close_pipe(); }
}
public Boolean Is_connected_to_server() {
return clientStream.IsConnected;
}
public void close_pipe()
{
if (clientStream != null)
{
if (clientStream.IsConnected)
{
clientStream.Close();
clientStream.Dispose();
Debug.WriteLine(" Pipe Closed");
}
}
}
}
}
Server side Main method implementation
static void Main(string[] args)
{
Asynchronus_NamedPipe_Server Async_server = new Asynchronus_NamedPipe_Server("mypipe7055");
while (true)
{
do
{
Async_server.Write_to_Client_Async("yeye");
Console.WriteLine("escape key");
} while (Console.ReadKey(true).Key != ConsoleKey.Escape);
}
}
Server Side Class -----
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Pipes;
using System.IO;
using System.ComponentModel;
using System.Diagnostics;
namespace Application_Pipe
{
public class Asynchronus_NamedPipe_Server
{
public readonly string pipe_address;
private System.IO.Pipes.NamedPipeServerStream namedPipeServerStream;
private string Server_Message;
public delegate void ASYNC_pipe_status_callback(string message);
private byte[] read_buffer = new byte[1024];
private byte[] write_buffer = new byte[1024];
public Asynchronus_NamedPipe_Server(string pipe_address)
{
try
{
this.pipe_address = pipe_address;
namedPipeServerStream = new NamedPipeServerStream(this.pipe_address,
PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous); //new NamedPipeServerStream(pipe_address);
Console.WriteLine("Connecting to Client...");
namedPipeServerStream.WaitForConnection();
Console.WriteLine("Connected to Client");
Read_from_Client_Async();
}
catch (Exception oEX) { Console.WriteLine(oEX.Message); }
}
public void Write_to_Client_Async(string message)
{
if (namedPipeServerStream != null)
{
if (namedPipeServerStream.CanWrite && namedPipeServerStream.IsConnected)
{
namedPipeServerStream.WaitForPipeDrain();
ASCIIEncoding.ASCII.GetBytes(message).CopyTo(write_buffer,0);
namedPipeServerStream.BeginWrite(write_buffer, 0, write_buffer.Length, new AsyncCallback(Async_Write_Completed), 2);
}
else { close_pipe(); }
}
}
public void Read_from_Client_Async()
{
if (namedPipeServerStream != null)
{
if (namedPipeServerStream.CanRead && namedPipeServerStream.IsConnected)
{
namedPipeServerStream.BeginRead(read_buffer, 0, read_buffer.Length, new AsyncCallback(Async_Read_Completed), 1);
} else { close_pipe(); }
}
}
private void Async_Read_Completed(IAsyncResult result)
{
namedPipeServerStream.EndRead(result);
this.Server_Message = ASCIIEncoding.ASCII.GetString(read_buffer);
this.Server_Message.Trim();
Debug.WriteLine("Received from Client => " + this.Server_Message+" <=REnd");
Read_from_Client_Async();
}
private void Async_Write_Completed(IAsyncResult result)
{
namedPipeServerStream.EndWrite(result);
Debug.WriteLine("Written To Client => " + ASCIIEncoding.ASCII.GetString(write_buffer));
}
public Boolean Is_connected_to_server()
{
return this.namedPipeServerStream.IsConnected;
}
public void close_pipe()
{
if(namedPipeServerStream.IsConnected){
namedPipeServerStream.Disconnect();
}
namedPipeServerStream.Close();
namedPipeServerStream.Dispose();
Debug.WriteLine(" Pipe Closed");
}
} //------class End
}
I'm trying to create a server (a computer with Bluetooth) that listen to Bluetooth messages. I'm using 32 feet library. But I'm getting a exception, and I cannot find what it is.
The exception is:
No supported Bluetooth protocol stack found.
here is the code:
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using InTheHand;
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Ports;
using InTheHand.Net.Sockets;
using System.IO;
namespace Bluetoot_Tutorial
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void bGo_Click(object sender, EventArgs e)
{
connectAsServer();
}
private void connectAsServer()
{
Thread bluetoothServerThread = new Thread(new ThreadStart(ServerConnectThread));
bluetoothServerThread.Start();
}
private void connectAsClient()
{
throw new NotImplementedException();
}
Guid uUUID = new Guid("00001101-0000-1000-8000-00805F9B34FB");
public void ServerConnectThread()
{
BluetoothListener blueListener = new BluetoothListener(uUUID);
blueListener.Start();
BluetoothClient conn = blueListener.AcceptBluetoothClient();
}
The message means what it says... What Bluetooth software do you have on your PC?
Add Local address in BluetoothListener like below.
BluetoothRadio myRadio = BluetoothRadio.PrimaryRadio;
if (myRadio == null)
{
Console.WriteLine("No radio hardware or unsupported software stack");
return;
}
RadioMode mode = myRadio.Mode;
var lsnr = new BluetoothListener(myRadio.LocalAddress, serviceClass);
lsnr.Start();