I want to connect unity app on android with a computer application. I could run it on the network but over internet it is always saying the machine is refusing the connection. I have disabled the firewall of windows and anti-virus but still have problem connecting the server and Android client:
No connection could be made because the target machine actively refused it.
Here is the code:
Server side:
TcpListener tcpListener;
Socket socket;
NetworkStream networkStream;
Thread thread;
string getIpAddress()
{
System.Net.IPHostEntry host;
string localIp = "";
host = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
foreach (System.Net.IPAddress ip in host.AddressList)
{
localIp = ip.ToString();
}
return localIp;
}
public void ReceiveImage()
{
try
{
IPAddress localAddr = IPAddress.Parse("95.171.54.53");
tcpListener = new TcpListener(localAddr, 53100);
tcpListener.Start();
socket = tcpListener.AcceptSocket();
networkStream = new NetworkStream(socket);
pictureBox1.Image = Image.FromStream(networkStream);
if (socket.Connected == true)
{
while (true)
{
tcpListener.Stop();
ReceiveImage();
}
}
}
catch(Exception ex)
{
string Message = ex.Message;
}
}
private void Form1_Load(object sender, EventArgs e)
{
thread = new Thread(new ThreadStart(ReceiveImage));
thread.Start();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
tcpListener.Stop();
thread.Abort();
}
This is the client side:
// Update is called once per frame
int frameSaveCount = -1;
int FrameCount = -1;
Socket socket;
NetworkStream networkStream;
Thread thread;
MemoryStream memoryStream;
TcpClient tcpClient;
BinaryWriter binaryWriter;
void Update()
{
// ...
if(FrameCount % 10==0)
{
// ...
send(bytes);
}
}
void send(Byte[] bytes)
{
try
{
print(getIpAddress());
tcpClient = new TcpClient("95.171.54.53", 53100);
networkStream = tcpClient.GetStream();
binaryWriter = new BinaryWriter(networkStream);
binaryWriter.Write(bytes);
binaryWriter.Close();
networkStream.Close();
tcpClient.Close();
}
catch (Exception exception)
{
string message = exception.Message;
print(message);
}
}
the machine is refusing the connection
This error has exactly one meaning: nothing was listening at the IP:port you tried to connect to. So, either it was wrong, or your server wasn't started when your client tried to connect.
Image files have precisely nothing to do with it.
Related
I have a tcp connection program. There are client and server sides. Client sides file is working on unity as script. Server sides file is working on main pc and as desktop application. When I open server and client files, they work on pc. If I also seperate this files to different pc's and again , they work. Up to here there is no any problem. However, if I want to build this client sides script file -which is on unity- as android apk and move it to my mobile device, client sides file is working but not connect to server. On computers, there is no any error, but apk file has error.
C# Server Side Code--
public Form1()
{
InitializeComponent();
}
//public virtual System.Windows.Forms.AnchorStyles Anchor { get; set; }
private void Form1_Load(object sender, EventArgs e)
{
Console.WriteLine(string.Format("Starting TCP and UDP servers on port {0}...", 27015));
devices_battery_midlow_pic_1.Visible = false;
devices_battery_low_pic_1.Visible = false;
devices_battery_midhigh_pic_1.Visible = false;
devices_battery_high_pic_1.Visible = false;
play_button.Anchor = (AnchorStyles.Bottom);
Console.WriteLine(DateTime.Now.ToString() + " Getting IP...");
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPAddress ipAddress2 = ipHostInfo.AddressList[1];
connection_id_label.Text = "This IP:\n" + ipAddress2.MapToIPv4().ToString();
Console.WriteLine(DateTime.Now.ToString() + " Starting Connection Thread...");
connectionThread = new Thread(new ThreadStart(StartServer));
connectionThread.IsBackground = true;
connectionThread.Start();
}
private void StartServer()
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
TcpListener listener = new TcpListener(IPAddress.Any, 27015);
listener.Start();
while (true)
{
using (TcpClient client = listener.AcceptTcpClient())
{
using (NetworkStream stream = client.GetStream())
{
byte[] buffer = new byte[client.ReceiveBufferSize];
int bytesRead = stream.Read(buffer, 0, client.ReceiveBufferSize);
string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine($"Received: {dataReceived}");
//Thread staThread = new Thread(() => PasteText(dataReceived));
//staThread.SetApartmentState(ApartmentState.STA);
//staThread.Start();
}
}
}
}
Client Side C# Script--
void Start()
{
Debug.Log(string.Format("Starting TCP and UDP clients on port {0}...", 116));
//udpThread = new Thread(new ThreadStart(ClientThread));
//udpThread.Start();
ClientThread();
}
// Update is called once per frame
void Update()
{
}
void OnGUI()
{
if (GUI.Button(new Rect(10, 10, 150, 100), debugString))
{
print("You clicked the button!");
}
}
void ClientThread()
{
using (TcpClient client = new TcpClient("10.10.10.73", 27015))
{
using (NetworkStream stream = client.GetStream())
{
byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes("asdasd");
stream.Write(bytesToSend, 0, bytesToSend.Length);
}
}
}
It is too important for me. I'm waiting your help.
below is some connection demo from my other projects. It works on Android/iOS/Mac/PC without issue & tested. I used Loom for easy threading, you may grab it from somewhere github maybe.
or maybe just the way you type IP. It should be sth like this.
string IP = "127.0.0.1";
client.BeginConnect(IPAddress.Parse(IP), ClientListenPort, ClientEndConnect, null);
This is my working server listener:
//create listener
listener = new TcpListener(IPAddress.Any, ClientListenPort);
listener.Start();
listener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
Loom.RunAsync(() => {
while (!stop)
{
// Wait for client connection
clients.Add(listener.AcceptTcpClient());
clients[clients.Count - 1].NoDelay = true;
// We are connected
isConnected = true;
streams.Add(clients[clients.Count - 1].GetStream());
streams[streams.Count - 1].WriteTimeout = 500;
Loom.QueueOnMainThread(() => {
isConnected = true;
});
System.Threading.Thread.Sleep(1);
}
});
This is my working client demo connection:
Loom.RunAsync(() => {
// if using the IPAD
//client.Connect(IPAddress.Parse(IP), ClientListenPort);
client.BeginConnect(IPAddress.Parse(IP), ClientListenPort, ClientEndConnect, null);
while (!client.Connected)
{
System.Threading.Thread.Sleep(1);
}
//do sth...
});
void ClientEndConnect(IAsyncResult result)
{
client.EndConnect(result);
}
Any help on the issue below would be highly appreciated. I'm using the StreamSocketListener Class to accept TCP/IP connection on my Raspberry Pi 3 running windows IoT 10 Core.
This is my server code so far:
static string _maintenancePort = "8888";
public async static void StartListening()
{
try
{
StreamSocketListener listener = new StreamSocketListener();
var currentSetting = listener.Control.QualityOfService;
listener.Control.QualityOfService = SocketQualityOfService.LowLatency;
listener.ConnectionReceived += SocketListener_ConnectionReceived;
listener.Control.KeepAlive = true;
await listener.BindServiceNameAsync(_maintenancePort);
}
catch (Exception e)
{
Log.WriteErrorLog(e);
}
}
private static async void SocketListener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
try
{
Log.WriteDebugLog("Incoming data...");
Stream inStream = args.Socket.InputStream.AsStreamForRead();
StreamReader reader = new StreamReader(inStream);
string request = await reader.ReadLineAsync();
if (request != null)
{
Log.WriteDebugLog("Received : " + request);
}
}
catch (Exception e)
{
Log.WriteErrorLog(e);
}
}
I wrote the following client code to connect to the socket. This code runs on another machine.
// ManualResetEvent instances signal completion.
private static ManualResetEvent connectDone = new ManualResetEvent(false);
private static ManualResetEvent sendDone = new ManualResetEvent(false);
private static ManualResetEvent receiveDone = new ManualResetEvent(false);
private static String response = String.Empty;
public static Socket client;
public static string SendMessageToClient(string ip, int port, string message, bool expectResponse)
{
// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
IPAddress ipAddress = IPAddress.Parse(ip);
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
// Create a TCP/IP socket.
client = new Socket(ipAddress.AddressFamily,SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();
message += "^" + expectResponse.ToString();
// Send test data to the remote device.
Send(client, message);
sendDone.WaitOne();
// Receive the response from the remote device.
if (expectResponse)
{
Receive(client);
receiveDone.WaitOne();
}
// Release the socket.
client.Shutdown(SocketShutdown.Both);
client.Close();
return response;
}
catch (Exception e)
{
Log.Write(e, false);
return "";
}
}
private static void Send(Socket client, 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.
client.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), client);
}
private static void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = client.EndSend(ar);
Log.WriteSingleMessage(String.Format("Sent {0} bytes to server.", bytesSent), false);
// Signal that all bytes have been sent.
sendDone.Set();
}
catch (Exception e)
{
Log.Write(e, false);
}
}
}
The client code is triggered by a button click event. The problem that I'm facing is that the server code above only works once. If I send a message to the server with the client code, the server processes the string perfect. However, if I hit the button a second time, the SocketListener_ConnectionReceived event is triggered but no data is coming in. I've tried several classes for ConnectionReceived but they all behave the same.
I checked with netstat on the Raspberry Pi if the server is listening and it is.
TCP 0.0.0.0:8888 0.0.0.0:0 LISTENING
Even child processes are created for handling the connection as you would expect from an Async calls. The client code closes the socket after it received a message that the data has been send (waitOne()) and the socket on the client machines changes to CLOSE_WAIT.
TCP 10.0.102.10:8888 10.0.100.11:31298 CLOSE_WAIT
TCP 10.0.102.10:8888 10.0.100.11:31299 ESTABLISHED
Can anyone help me out and point me in the right direction as to what I'm doing wrong. any help would be highly appreciated.
You can try to use synchronous methods instead asynchronous methods for socket client. It will work. Please refer to following code:
public void SendMessageToClientSync(string ip, int port, string message, bool expectResponse)
{
// 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(ip);
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
// 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(message);
// Send the data through the socket.
int bytesSent = sender.Send(msg);
if(expectResponse)
{
// 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());
}
}
I am trying to write a TCP listener that can connect to multiple clients and send and receive data.
Some of my code -
Calling server -
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'cresijCamDataSet1.CentralControl' table. You can move, or remove it, as needed.
this.centralControlTableAdapter1.Fill(this.cresijCamDataSet1.CentralControl);
s = new Server();
Thread th = new Thread(s.Run);
th.Start();
}
Run Method -
public async void Run()
{
tcp = new TcpListener(IPAddress.Any, 1200);
tcp.Start();
while (true)
{
try
{
TcpClient client = await tcp.AcceptTcpClientAsync();
Thread th = new Thread(()=>{
Process(client);
}) ;
}
catch (Exception ex)
{
string m = ex.Message;
}
}
}
private async Task Process(TcpClient tcpClient)
{
bool hasItem = clients.Contains(tcpClient);
if(hasItem == false)
{
clients.Add(tcpClient);
}
IPEndPoint iPEndPoint =(IPEndPoint) tcpClient.Client.RemoteEndPoint;
string ip = ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address.ToString();
NetworkStream stream = tcpClient.GetStream();
byte[] receivedBytes = new byte[tcpClient.ReceiveBufferSize];
stream.Read(receivedBytes, 0, receivedBytes.Length);
f.UpdateData(receivedBytes, ip);
}
Sender Method to send data -
public void Sender(byte[] data, TcpClient client)
{
NetworkStream stream = client.GetStream();
stream.Write(data, 0, data.Length);
}
As you can see I have called Run() method in formLoad. But this all is not working as I dont have much knowledge of threads.
This method is not continuous. The server is not listening to clients always. Can someone help me with this. I need asynchronuous tcp listener that can listen to incoming clients and that too in windows form. Console Server I have.
I created server where I wait for data. When I call AcceptAsync the handling method connectArgs_Accepted is called and that causes exceptions and crash even when method is empty iniside. How to deal with that?
Thread thread = new Thread(new ThreadStart(connect));
thread.Start();
}
Socket connection;
SocketAsyncEventArgs connectArgs;
string ip = "192.168.0.13";
int port = 13001;
private void connect() {
connectArgs = new SocketAsyncEventArgs { RemoteEndPoint = new DnsEndPoint(ip, port) };
connectArgs.Completed += connectArgs_Accepted;
connection = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
connection.AcceptAsync(connectArgs);
}
void connectArgs_Accepted(object sender, SocketAsyncEventArgs e) {//that causes exception
/* if (e.SocketError == SocketError.Success) {
// data sent
try {
Receive();
} catch (Exception ex) { Console.WriteLine(ex); }
} else {
// error
}*/
}
Output:
System.InvalidOperationException: Socket must be bound to a local endpoint to perform this operation.
at System.Net.Sockets.Socket.AcceptAsync(SocketAsyncEventArgs e)
at HomeSecurityClient.JPGServer.connect()
The thread 0x458 has exited with code 259 (0x103).
.
The Client side(sender)
namespace HomeSecurity {
//singleton
public class JPGClient {
IPAddress ip;
int port;
public static JPGClient JPG_CLIENT = null;
public JPGClient(IPAddress ip, int port) {
this.ip = ip;
this.port = port + 1;
JPG_CLIENT = this;
Thread thread = new Thread(new ThreadStart(sendjpg));
thread.Start();
}
public void sendjpg() {
TcpClient client = new TcpClient();
try {
System.Diagnostics.Debug.WriteLine(ip + " X " + 13001);
client.Connect(ip, 13001);
System.Diagnostics.Debug.WriteLine(ip + " polaczzyl X " + 13001);
// Retrieve the network stream.
NetworkStream stream = client.GetStream();
ImageBrush imageBrush = new ImageBrush();
imageBrush.ImageSource = new BitmapImage(new Uri(#"C:\a.jpg", UriKind.Absolute));
MessageData data = new MessageData(imageBrush);
IFormatter formatter = new BinaryFormatter();
while (true) {
System.Diagnostics.Debug.WriteLine("SLEEEEEEEEEEEEEEE");
formatter.Serialize(stream, data);
Thread.Sleep(1000);
// data.GetNewImage();
}
} catch (Exception e) { System.Diagnostics.Debug.WriteLine(e); }
}
}
}
Server sockets (that accept client connections) should be bound to the local network interface and port first.
Before calling AcceptAsync you should bind socket to the local endpoint.
Have a look at Socket.Bind info (http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.bind(v=vs.110).aspx)
I am trying to establish a communication between a handheld and a PC.
I have the following code, for the client:
public void connect(string IPAddress, int port)
{
// Connect to a remote device.
try
{
IPAddress ipAddress = new IPAddress(new byte[] { 192, 168, 1, 10 });
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
// Create a TCP/IP socket.
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client);
if (connectDone.WaitOne()){
//do something..
}
else{
MessageBox.Show("TIMEOUT on WaitOne");
}
}
catch(Exception e){
MessageBox.Show(e.Message);
}
}
My problem is that when I run both of them in a pc they communicate fine, but the same code in a SmartDevice Project doesn't connect with the Server which is running on the PC and it give me this error:
System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or stablished connection failed
because connected host has failed to respond
What am I missing?
NOTE: The IPAddress is hard coded inside the code
EDIT: here is another code which I take from a MSDN example. This don't work either, it says that it not possible to read. The server code in this case is the same as the example, the client code have a modification:
private void button1_Click(object sender, EventArgs e)
{
// In this code example, use a hard-coded
// IP address and message.
string serverIP = "192.168.1.10";//HERE IS THE DIFERENCE
string message = "Hello";
Connect(serverIP, message);
}
Thanks in advance for any help!
For my "mobile device" client, I send data to the "PC" host using this:
private void Send(string value) {
byte[] data = Encoding.ASCII.GetBytes(value);
try {
using (TcpClient client = new TcpClient(txtIPAddress.Text, 8000)) {
NetworkStream stream = client.GetStream();
stream.Write(data, 0, data.Length);
}
} catch (Exception err) {
// Log the error
}
}
For the host, you're best to use a thread or BackgroundWorker where you can let a TcpListener object sit and wait:
private void Worker_TcpListener(object sender, DoWorkEventArgs e) {
BackgroundWorker worker = (BackgroundWorker)sender;
do {
string eMsg = null;
int port = 8000;
try {
_listener = new TcpListener(IPAddress.Any, port);
_listener.Start();
TcpClient client = _listener.AcceptTcpClient(); // waits until data is avaiable
int MAX = client.ReceiveBufferSize;
NetworkStream stream = client.GetStream();
Byte[] buffer = new Byte[MAX];
int len = stream.Read(buffer, 0, MAX);
if (0 < len) {
string data = Encoding.UTF8.GetString(buffer);
worker.ReportProgress(len, data.Substring(0, len));
}
stream.Close();
client.Close();
} catch (Exception err) {
// Log your error
}
if (!String.IsNullOrEmpty(eMsg)) {
worker.ReportProgress(0, eMsg);
}
} while (!worker.CancellationPending);
}