I'm trying to establish a TCP connexion between a C# Xamarin Android app and a C++ app on a Raspberry pi.
On the C# client side, I'm using the TcpClient client from System.Net.Sockets :
// C#
static public bool Connect(string IP, string port)
{
bool _connected = false;
try
{
client = new TcpClient();
IPAddress _ip = IPAddress.Parse(IP);
int _port = int.Parse(port);
client.Connect(_ip, _port);
_connected = true;
}
catch
{
_connected = false;
}
return _connected;
}
This is a pretty straight forward use of the TcpClient class as you can see.
On the server side, using SDL_Net (1.2), here is my socket init :
// C++
string mNet::Resolve()
{
socketSet = SDLNet_AllocSocketSet(2);
if(socketSet == NULL)
return "Could not allocate socket set : " + string(SDLNet_GetError());
if(SDLNet_ResolveHost(&serverIP, NULL, Prefs::NET_PORT) == -1)
return "Could not resolve server host : " + string(SDLNet_GetError());
serverSocket = SDLNet_TCP_Open(&serverIP);
if(!serverSocket)
return "Could not create server socket : " + string(SDLNet_GetError());
SDLNet_TCP_AddSocket(socketSet, serverSocket);
return "OK";
}
and here is a dummy listener for testing :
// C++
void mNet::Update()
{
int serverSocketActivity = SDLNet_SocketReady(serverSocket);
if (serverSocketActivity != 0)
{
if(!ClientConnected) // new connection
{
clientSocket = SDLNet_TCP_Accept(serverSocket);
SDLNet_TCP_AddSocket(socketSet, clientSocket);
ClientConnected = true;
SendToClient("1");
Logger::Log("Client connected !");
}
else // server busy
{
SendToClient("0", true);
Logger::Log("Client refused !");
}
}
}
I get no error from the initialization, and when I run a netstat -an | grep tcp command on the raspberry, I can see the port i'm using (1234) opened.
But when I try to connect from the android emulator, it seems that nothing is happening server side (no socket activity).
IP & ports are matching.
I'm not really used to networking, so is there something I'm doing wrong here ?
Additional info :
Targeting Android 6
RaspberryPi is running UbunutuMate
Networking C# class : https://github.com/arqtiq/RemotePlayerPi/blob/master/App/Network.cs
Networking C++ class : https://github.com/arqtiq/RemotePlayerPi/blob/master/Server/src/mNet.cpp
Thanks !
Related
I am able to:
ssh -p 8811 myuser#74.xxx.xxx.xxx
Then from within that machine, can run a program that successfully establishes socket connection at 10.xx.xxx.xxx on port 32060.
I am trying to convert it to a local C# program that does the ssh + socket connection without having to keep the ssh open on my terminal, so I can just run the program.
It is able to successfully ssh in, then ping the 10.xx.xxx.xxx address, but cannot establish the socket connection. Am I missing a step?
using (var client = new SshClient("74.xxx.xxx.xxx", 8811, "myuser", privatekey))
{
client.Connect();
string host = "10.xx.xxx.xxx";
int port = 32060;
if (client.IsConnected)
{
Console.WriteLine("ssh connected");
SshCommand cmd = client.CreateCommand($"ping -c 3 {host}");
cmd.Execute();
Console.WriteLine(cmd.Result); // successfully pings 10.xx.xxx.xxx
TcpClient tcpClient = new TcpClient();
tcpClient.Connect(new IPEndPoint(IPAddress.Parse(host), port));
Console.WriteLine("tcp connected"); // fails, times out when trying 10.xx.xxx.xxx:32060
}
client.Disconnect();
}
I was able to get this to work using a package called Chilkat socket.UseSsh(): https://www.chilkatsoft.com/refdoc/csSocketRef.html#method91
string sshUsername = "myuser";
string sshHostname = "74.xxx.xxx.xxx";
int sshPort = 8811;
string socketHostname = "10.xx.xxx.xxx";
int socketPort = 32060;
// === SSH ===
Chilkat.Ssh ssh = new Chilkat.Ssh();
Chilkat.SshKey sshkey = new Chilkat.SshKey();
sshkey.FromOpenSshPrivateKey(#"xxx");
bool success = ssh.Connect(sshHostname, sshPort);
if (success != true)
{
Console.WriteLine(ssh.LastErrorText);
return;
}
success = ssh.AuthenticatePk(sshUsername, sshkey);
if (success != true)
{
Console.WriteLine(ssh.LastErrorText);
return;
}
// === Socket ===
Chilkat.Socket socket = new Chilkat.Socket();
success = socket.UseSsh(ssh);
if (success != true)
{
Console.WriteLine(socket.LastErrorText);
return;
}
bool useTls = false;
int maxWaitMillisec = 20000;
success = socket.Connect(socketHostname, socketPort, useTls, maxWaitMillisec);
if (success != true)
{
Console.WriteLine(socket.LastErrorText);
return;
}
Good afternoon dear community,
I am currently working on a Arduino + Unity project where I am supposed to build an Arduino control through Unity. For that, I have set my Arduino and connected to wifi.
I built a Socket Server with C#. The problem is that: I am able to connect to this Socket Server through a Node.js Socket Client, however to check if my Arduino setup is broken, I have built a Node.js Socket Server and was able to connect my Node.js Socket server succesfully through Arduino. (The only reason I am using Node.js here is that because I am more fluent on that platform so I am able to check what is wrong, so final project does not have any Node.js.) So;
Node.js Client -> Unity C# Server (Works)
Arduino Client -> Node.js Server (Works) (Below is Arduino output)
AT+CIPSTART=3,"TCP","192.168.1.67",1234
OK
Linked
Arduino Client -> Unity C# Server (Does not work) (Below is Arduino output)
AT+CIPSTART=3,"TCP","192.168.1.67",1234
ERROR
Unlink
Below I am putting my all C#, Node.js and Arduino codes. I don`t think that there is an Arduino hardware issue here, but don·t understand why I cannot connect my
Unity Socket Server.
using System;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using UnityEngine;
public class SocketScript : MonoBehaviour {
Thread tcpListenerThread;
void Start()
{
tcpListenerThread = new Thread(() => ListenForMessages(1234));
tcpListenerThread.Start();
}
public void ListenForMessages(int port)
{
TcpListener server = null;
try
{
IPAddress localAddr = IPAddress.Parse("192.168.1.67");
server = new TcpListener(localAddr, port);
server.Start();
Byte[] bytes = new byte[256];
String data = null;
while(true)
{
Debug.Log("Waiting for connection.");
using (TcpClient client = server.AcceptTcpClient())
{
Debug.Log("Connected!");
data = null;
NetworkStream stream = client.GetStream();
int i;
// As long as there is something in the stream:
while((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Debug.Log(String.Format("Received: {0}", data));
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
// Send back a response.
stream.Write(msg, 0, msg.Length);
Debug.Log(String.Format("Sent: {0}", data));
}
}
}
} catch (SocketException e)
{
Debug.LogError(String.Format("SocketException: {0}", e));
} finally
{
server.Stop();
}
}
}
Node.js Client:
var net = require('net');
var HOST = '192.168.1.67';
var PORT = 1234;
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('Client connected to: ' + HOST + ':' + PORT);
// Write a message to the socket as soon as the client is connected, the server will receive it as message from the client
client.write('Hello World!');
});
client.on('data', function(data) {
console.log('Client received: ' + data);
if (data.toString().endsWith('exit')) {
client.destroy();
}
});
// Add a 'close' event handler for the client socket
client.on('close', function() {
console.log('Client closed');
});
client.on('error', function(err) {
console.error(err);
});
Node.js Server:
var net = require('net');
// Configuration parameters
var HOST = '192.168.1.67';
var PORT = 1234;
// Create Server instance
var server = net.createServer(onClientConnected);
server.listen(PORT, HOST, function() {
console.log('server listening on %j', server.address());
});
function onClientConnected(sock) {
var remoteAddress = sock.remoteAddress + ':' + sock.remotePort;
console.log('new client connected: %s', remoteAddress);
sock.on('data', function(data) {
console.log('%s Says: %s', remoteAddress, data);
sock.write(data);
sock.write(' exit');
});
sock.on('close', function () {
console.log('connection from %s closed', remoteAddress);
});
sock.on('error', function (err) {
console.log('Connection %s error: %s', remoteAddress, err.message);
});
};
I am a Newbie to TCP/IP programming in c#, so I am DESPERATE for a solution to my current problem!
I have designed a C# Windows application running under Windows 7 with a Sqlserver 2005 database. My application is trying to send an HL7 record over a TCP/IP connection, to a Unix Lab. system machine.
I can get a connection ok, and send the HL7. BUT I cannot get ANY reply from the Lab. server! the connection times-out with error code 10060, as well as a _COMPlusExceptionCode value of -532462766.
Here is a sample of my c# 'Connect' methods:
buildSendHL7_TCPIP hl7Agent = new buildSendHL7_TCPIP();
// class 'buildSendHL7_TCPIP(); ' contains methods to build the HL7 segments, as well as methods to send and receive messages over the TCP connection
string strServerIPAddress = string.Empty;
Int32 intSocketNo = new Int32();
bool sentOK = false;
/***********************************/
/*Try send the HL7 to LIS-HORIZON...*/
/***********************************/
strServerIPAddress = "10.1.6.248";
intSocketNo = 5910;
sentOK = hl7Agent.SendHL7(strServerIPAddress, intSocketNo, strHL7_Record);
if (!sentOK)
{
_strUIMessage = "*Error* HL7 Message NOT sent to LIS!";
opsMessageBox mb = new opsMessageBox(this);
mb.ShowDialog();
mb.Close();
goto EndLabel;
}
Here are the methods I've created to build a TCP connection and send the HL7 to the LIS Server:
public bool SendHL7(string strIPAddress, Int32 intSocket, string hl7message)
{
/* send the complete HL7 message to the server...*/
int port = (int)intSocket;
IPAddress localAddr = IPAddress.Parse(strIPAddress);
try
{
// Add the leading & trailing character field-separator and CR LineFeed' t.
string llphl7message = null;
llphl7message = "|";
llphl7message += hl7message;
llphl7message += Convert.ToChar(28).ToString();
llphl7message += Convert.ToChar(13).ToString();
// Get the size of the message that we have to send.
Byte[] bytesToSend = Encoding.ASCII.GetBytes(llphl7message);
Byte[] bytesReceived = new Byte[256];
// Create a socket connection with the specified server and port.
Socket s = ConnectSocket(localAddr, port);
// If the socket could not get a connection, then return false.
if (s == null)
return false;
// Send message to the server.
s.Send(bytesToSend, bytesToSend.Length, 0);
// Receive the response back
int bytes = 0;
s.ReceiveTimeout = 3000; /* 3 seconds wait before timeout */
bytes = s.Receive(bytesReceived, bytesReceived.Length, 0); /* IMEOUT occurs!!! */
string page = Encoding.ASCII.GetString(bytesReceived, 0, bytes);
s.Close();
// Check to see if it was successful
if (page.Contains("MSA|AA"))
{
return true;
}
else
{
return false;
}
}
catch (SocketException e)
{
MessageBox.Show("SocketExecptionError:" + e);
return false;
}
}
private static Socket ConnectSocket(IPAddress server, int port)
{
Socket s = null;
IPHostEntry hostEntry = null;
// Get host related information.
hostEntry = Dns.GetHostEntry(server);
foreach (IPAddress address in hostEntry.AddressList)
{
IPEndPoint ipe = new IPEndPoint(address, port);
Socket tempSocket = new Socket(ipe.AddressFamily,SocketType.Stream,ProtocolType.Tcp);
tempSocket.Connect(ipe);
if (tempSocket.Connected)
{
s = tempSocket;
break;
}
else
{
continue;
}
}
return s;
}
I've been told that socket 5910 cannot receive ANY communications in Windows 7 due to Virus issues. Is this true? If so, I tried to connect to ANOTHER server on our network (PACS/RIS) socket # 5556. I get the SAME timeout error message.
The behaviour looks like the server doesn't understand your request / doesn't recognize it as a complete message according to the expected protocol.
As I understand from your code you are sending a HL7 message. I don't know this protocol, according to google it could be Health Level 7. The example I found is starting with some text, then a | as a delimiter. Your message is starting with |. Maybe there is the problem...
So you should have a look if the message you send is matching the protocol definition.
I turned on my mobile's hotspot and connected my computer to the hotspot
and used this code to create server but InetAddress became "/0.0.0.0":
ServerSocket ss = null;
try {
ss= new ServerSocket(4444);
//texto.append("\n"+ss.getInetAddress());
Log.d("TcpServer", ss.getInetAddress()+"");
log= ss.getInetAddress().toString();
//ss.setSoTimeout(10000);
//accept connections
Socket s = ss.accept();
Log.i("TcpServer", "Receiving");
//texto.append("\n"+"Receiving");
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
//BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
//receive a message
Log.i("TcpServer", in.readLine());
final String incomingMsg = in.readLine() + System.getProperty("line.separator");
Log.i("TcpServer", "received: " + incomingMsg);
runOnUiThread(new Runnable() {
public void run() {
// texto.append("received: " + incomingMsg);
}
});
s.close();
Yes. If you just create a socket, the default is to listen on all network devices/all assigned IP addresses, which is reflected by listening on IP 0.0.0.0.
I'm new to Android programming and I'm trying to send some text data to PC via TCP.
I built an example I found on the web, which has an Android Client and a Java Server.
The server runs ok.
When I run the Android Client on the emulator or on the phone, both works perfectly well.
The problem is that I need it to communicate to a C# application, so I built an TCP server in C#.
Now, if I run the Client on the emulator it works and the C# server receive the data (a little messed, but it's probably an text encoding problem which I think won't be hard to solve). But anyway, the data is arriving at the c# server.
If I try to run the same Client on the phone I can't even connect to the C# server. I get a timeout error when connecting.
Also I can ping the PC from phone and ping the phone from PC, so I don't think it's a network problem.
I have some experience in C# but not much on sockets and even less on Android. So I ask, is there any difference on TCP protocols used by Java and C#? Sorry if it's a dumb question, but I googled it for hours and haven't found a clue.
Any ideas of what may be causing it?
The Java server code is this:
public class Servidor {
private static boolean executando = true;
private static String mensagem;
private static final int PORTA = 1234;
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(1234);
InetAddress addr = InetAddress.getLocalHost();
System.out.println("----------- SERVER CONNECTED "
+ addr.getHostAddress() + " PORT " + PORTA
+ " -----------");
System.out.println("Waiting connections.");
Socket socket = server.accept();
System.out.println("Server -> Connected Ip "
+ socket.getInetAddress().getHostAddress());
DataInputStream in = new DataInputStream(socket.getInputStream());
try {
while (executando) {
mensagem = in.readUTF();
System.out.println("Server-> Received Message: "
+ mensagem);
}
System.out.println("Servidor-> Finalizado.");
in.close();
socket.close();
server.close();
} catch (Exception e) {
System.err.println("Server -> Error: " + e.getMessage());
executando = false;
}
} catch (Exception e) {
e.printStackTrace();
}
} }
The C# Server code is this:
class Server
{
private TcpListener tcpListener;
private Thread listenThread;
public Server()
{
Console.WriteLine("\nStarting server...");
this.tcpListener = new TcpListener(IPAddress.Any, 1234);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
private void ListenForClients()
{
Console.WriteLine("\nWaiting for clients to connect...");
this.tcpListener.Start();
while (true)
{
blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
create a thread to handle communication
with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
private void HandleClientComm(object client)
{
Console.WriteLine("\nIncoming from client...");
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch
{
a socket error has occured
break;
}
if (bytesRead == 0)
{
the client has disconnected from the server
break;
}
message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
Console.WriteLine("\nReceived: \n\n" + encoder.GetString(message, 0, bytesRead));
}
tcpClient.Close();
}
}
If needed, the Android Client code is exactly the one on the following link:
http://www.portalandroid.org/comunidade/viewtopic.php?f=7&t=11077&p=127577