Android Server connect to C# Client - c#

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.

Related

How to have a C# TCP Chat Server listen for connections from multiple clients?

So this is code for my TCP based chat server written in c#. It works no problem for connecting two computers via ipv4 for chat, but I am wanting the server program to listen for and accept, then send a "sucessfully joined" message to the computers that joined.
I am wondering is there a way to change this code to do this?
Server code:
IPAddress ipAd = IPAddress.Parse(IPV4.Text); //use local m/c IP address, and use the same in the client
/* Initializes the Listener */
TcpListener myList = new TcpListener(ipAd, 8001);
/* Start Listeneting at the specified port */
myList.Start();
MessageBox.Show("The server is running at port 8001...");
MessageBox.Show("The local End point is :" + myList.LocalEndpoint);
MessageBox.Show("Looking for other computer");
Socket s = myList.AcceptSocket();
Console.WriteLine("Found buddy " + s.RemoteEndPoint);
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes(satt.Text));
MessageBox.Show("The message " + satt.Text + " was sent to the computer with IP address " + IPV4.Text);
byte[] b = new byte[100];
int k = s.Receive(b);
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(b[i]));
/* clean up */
s.Close();
myList.Stop();
Client code:
TcpClient tcpclnt = new TcpClient();
tcpclnt.Connect(RecieveIPAdd.Text, 8001); // use the ipaddress as in the server program
MessageBox.Show("Connected");
Stream stm = tcpclnt.GetStream();
MessageBox.Show("Listening for attack information......");
byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);
string atk = Encoding.UTF8.GetString(bb.AsSpan(0, k));
Thank you.
// Code after help
private void Connectnattk_DoWork(object sender, DoWorkEventArgs e)
{
{
{
try
{
IPAddress ipAd = IPAddress.Parse(IPV4.Text); //use local m/c IP address, and use the same in the client
/* Initializes the Listener */
TcpListener myList = new TcpListener(ipAd, 8001);
/* Start Listeneting at the specified port */
myList.Start();
MessageBox.Show("The server is running at port 8001...");
MessageBox.Show("The local End point is :" + myList.LocalEndpoint);
MessageBox.Show("Looking for other computer");
Socket s = myList.AcceptSocket();
Console.WriteLine("Found buddy " + s.RemoteEndPoint);
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes(satt.Text));
MessageBox.Show("The command " + satt.Text + " was sent to the computer with IP address " + IPV4.Text);
byte[] b = new byte[100];
int k = s.Receive(b);
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(b[i]));
void ServerStart()
{
TcpListener listener = new TcpListener(IPAddress.Any, 8001);
listener.Start();
Console.WriteLine("Listening on port: 8001");
while (true)
{
TcpClient client = listener.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(state => HandleConnection(client));
}
}
void HandleConnection(TcpClient client)
{
Socket s = myList.AcceptSocket();
Console.WriteLine("Found buddy " + s.RemoteEndPoint);
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes(satt.Text));
Console.WriteLine("Number of connected buddies: " + connectedbuddies++);
client.Close();
}
/* clean up */
s.Close();
myList.Stop();
}
Accepting a client socket in your code is synchronous, so you can only accept one client, process it then loop around to accept and process another.
You can use threads to add parallelism to your code. You create a method for handling client sockets and create a new thread for the client socket. This will allow you to continue looping to accept new incoming client socket connections whilst processing existing client socket connections.
static void ServerStart()
{
TcpListener listener = new TcpListener(IPAddress.Any, 4480);
listener.Start();
Console.WriteLine("Listening on port: 4480");
while (true)
{
// Accept the client connection before creating the thread.
TcpClient client = listener.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(state => HandleConnection(client));
}
}
static void HandleConnection(TcpClient client)
{
// Insert your code here. (Do not accept socket again here)
client.Close();
}
I create a new thread to run the HandleConnection method for each TcpClient using ThreadPool. You can create threads without ThreadPool however if threads are short-lived for performance reasons, you will want to use ThreadPool to create them.

TCP Server only works in localhost scheme

I can establish a TCP connection between a TCP client and TCP server in localhost, however I can't repeat the same example for a connection with different computers into the same net range (sender Windows Server 2012 x64 R2 and receiver Windows 10 x64 Pro) . The TCP Server is a C# application and the TCP client is in node.js. I have disabled both Antivirus and Windows Firewall.
//SERVER C#
void Receive() {
//tcp_Listener = new TcpListener(IPAddress.Parse("192.168.1.62"), 212);
IPAddress localAddr = IPAddress.Parse("0.0.0.0");
tcp_Listener = new TcpListener(localAddr,212);
TcpClient clientSocket = default(TcpClient);
tcp_Listener.Start();
print("Server Start");
while (mRunning)
{
// check if new connections are pending, if not, be nice and sleep 100ms
if (!tcp_Listener.Pending()){
Thread.Sleep(10);
}
else {
clientSocket = tcp_Listener.AcceptTcpClient();
NetworkStream networkStream = clientSocket.GetStream();
byte[] bytesFrom = new byte[10025];
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
if (dataFromClient != "") {
print ("Data from client: " + dataFromClient);
} else {
print ("Client no data");
}
clientSocket.Close();
}
}
}
//CLIENT NodeJS
var net = require('net');
var HOST = '192.168.0.136';
var PORT = 212;
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('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('MSG SENT!');
});
// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function(data) {
console.log('DATA: ' + data);
// Close the client socket completely
client.destroy();
});
// Add a 'close' event handler for the client socket
client.on('close', function() {
console.log('Connection closed');
});
The wireshark log about this whole connection is the following:
This is the log from TCP Client:
I have replaced for networkStream.Read (bytesFrom, 0, bytesFrom.Length)

Android and c# tcp communication

I want to send a message from a C# application to the Android emulator or device over TCP. I have searched on Google and got the maximum results for Android client and C# server but not what I want to acheive.
Here is what I have tried; maybe I am going about it the wrong way but what I want is to send a message over TCP to an Android device.
Server Code to send a message:
private static int port = 4444;
private static TcpListener listener;
private static Thread thread;
private static int clientId = 0;
listener = new TcpListener(new IPAddress(new byte[] { 127, 0, 0, 1 }), port);
thread = new Thread(new ThreadStart(Listen));
thread.Start();
private static void Listen()
{
listener.Start();
MessageBox.Show("Listening on: " + port.ToString());
while (true)
{
MessageBox.Show("Waiting for connection....");
MessageBox.Show("Client No: " + clientId);
TcpClient client = listener.AcceptTcpClient();
Thread listenThread = new Thread(new ParameterizedThreadStart(ListenThread));
listenThread.Start(client);
}
}
private static void ListenThread(Object client)
{
NetworkStream netstream = ((TcpClient)client).GetStream();
MessageBox.Show("Request made");
clientId = clientId + 1;
// String message = "Hello world";
byte[] resMessage = Encoding.ASCII.GetBytes(clientId.ToString());
netstream.Write(resMessage, 0, resMessage.Length);
netstream.Close();
}
Client Code
private TextView textDisplay;
Socket socket;
private static final int TCP_SERVER_PORT = 4444;
ServerSocket ss = null;
try {
ss = new ServerSocket(TCP_SERVER_PORT);
//ss.setSoTimeout(10000);
//accept connections
Socket s = ss.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
//receive a message
String incomingMsg = in.readLine() + System.getProperty("line.separator");
Log.d("TcpServer", "received: " + incomingMsg);
textDisplay.append("received: " + incomingMsg);
//send a message
String outgoingMsg = "goodbye from port " + TCP_SERVER_PORT + System.getProperty("line.separator");
out.write(outgoingMsg);
out.flush();
Log.d("TcpServer", "sent: " + outgoingMsg);
textDisplay.append("sent: " + outgoingMsg);
//SystemClock.sleep(5000);
s.close();
} catch (InterruptedIOException e) {
//if timeout occurs
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
Log.d("Error",e.toString());
}
}
}
The problem lies in your Client code.
A socket is opened between two parties, one that plays the role of the listener / server that does bind->listen->accept and a client that connect
In your code there are two problems:
Your client should connect and not accept
Both your client and your server will try to read from the socket and write afterwards. There would be no problem if your read and write operations from the socket were on different threads.In your case this will result in a deadlock.
If you want both operations to be done on the same thread , sequentially then your client and server should perform the read and write in opposite order :
Client : read -> write
Server: write-> read

Android socket client works on Java server but not C# server

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

TCP/UDP Socket server on WAN

I have written a socket server in c# that will be used as the basic design for a small game project I am part of. The socket server works fine on lan. I able to communicate completely fine between the server and the client. However on the WAN the server receives all the correct messages from the client, but the client receives no messages from the server. Both the client and the server are behind a router but only the server's router has the ports forwarded. When the client connects to the server I get the IP address of the connection. Because the client is behind a NAT, is there more information from the sender that I need to collect? I assume the client could set up port forwarding but that would be VERY counter-productive to the game. Any help I can get is appreciated. If you need code let me know. Thanks in advance.
Used to make the TCP connection from the client
public string ConnectionAttempt(string ServeIP, string PlayUsername)
{
username = PlayUsername;
try
{
connectionClient = new TcpClient(ServeIP,TCP_PORT_NUMBER);
connectionClient.GetStream().BeginRead(readbuffer, 0, READ_BUFFER_SIZE, new AsyncCallback(DoRead), null);
Login(username);
ipAddress = IPAddress.Parse(((IPEndPoint)connectionClient.Client.RemoteEndPoint).Address.ToString());
servIP = new IPEndPoint(ipAddress,65002);
listenUDP = new IPEndPoint(ipAddress, 0);
UDPListenerThread = new Thread(receiveUDP);
UDPListenerThread.IsBackground = true;
UDPListenerThread.Start();
return "Connection Succeeded";
}
catch(Exception ex) {
return (ex.Message.ToString() + "Connection Failed");
}
}
Listens for a UDP message on a thread.
private void receiveUDP()
{
System.Net.IPEndPoint test = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0);
System.Net.EndPoint serverIP = (System.Net.EndPoint)test;
server.Bind(serverIP);
EndPoint RemoteServ = (EndPoint)servIP;
while (true)
{
byte[] content = new byte[1024];
int data = server.ReceiveFrom(content, ref RemoteServ);
string message = Encoding.ASCII.GetString(content);
result = message;
ProcessCommands(message);
}
}
Server TCP connection Listener:
private void ConnectionListen()
{
try
{
listener = new TcpListener(System.Net.IPAddress.Any, PORT_NUM);
listener.Start();
do
{
UserConnection client = new UserConnection(listener.AcceptTcpClient());
client.LineRecieved += new LineRecieve(OnLineRecieved);
UpdateStatus("Someone is attempting a login");
} while (true);
}
catch
{
}
}
Server UDP Listener:
private void receiveUDP()
{
System.Net.IPEndPoint test = new System.Net.IPEndPoint(System.Net.IPAddress.Any, UDP_PORT);
System.Net.EndPoint serverIP = (System.Net.EndPoint)test;
trans.Bind(serverIP);
System.Net.IPEndPoint ipep = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0);
System.Net.EndPoint Remote = (System.Net.EndPoint)ipep;
while (true)
{
byte[] content = new byte[1024];
int recv = trans.ReceiveFrom(content,ref Remote);
string message = Encoding.ASCII.GetString(content);
string[] data = message.Split((char)124);
//UpdateStatus(data[0] + data[1]);
UserConnection sender = (UserConnection)clients[data[0]];
sender.RemoteAdd = Remote;
if (data.Length > 2)
{
OnLineRecieved(sender, data[1] + "|" + data[2]);
}
else
{
OnLineRecieved(sender, data[1]);
}
}
}
Setup Information for a user connection Server-side:
Socket trans = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp); //UDP connection for data transmission in game.
public PlayerLoc Location = new PlayerLoc();
public UserConnection(TcpClient client)//TCP connection established first in the Constructor
{
this.client = client;
ipAdd = IPAddress.Parse(((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString());
ipep = new IPEndPoint(ipAdd, ((IPEndPoint)client.Client.RemoteEndPoint).Port);
this.client.GetStream().BeginRead(readBuffer, 0, READ_BUFFER_SIZE, new AsyncCallback(StreamReciever), null);
}
Method for sending data to individual users:
public void SendData(string data)//UDP only used during transmission
{
byte[] dataArr = Encoding.ASCII.GetBytes(data);
trans.SendTo(dataArr, dataArr.Length,SocketFlags.None, RemoteAdd);
}
The client must start the UDP communication so that it can get a "hole" in the router/firewall. And the UDP server must reply back using the end point referenced in ReceviedFrom

Categories

Resources