Android socket connection with a server - c#

I'm trying to connect my Android phone with a Server. On the Server runs a program written in C#. I've tryed to make it with the following code but it doesn't work.
This is the Android code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Socket socket;
int port = 52301;
String ip = "79.16.115.30";
Button b = (Button) findViewById(R.id.myButton);
assert b != null;
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
byte[] b = ip.getBytes();
/*SocketAddress socketAddress = new InetSocketAddress(ip, port);
socket.connect(socketAddress);*/
socket = new Socket(ip, port);
Toast.makeText(v.getContext(), "CONNESSO", Toast.LENGTH_SHORT).show();
} catch (UnknownHostException e) {
Toast.makeText(v.getContext(), "CHI MINCHIA รจ COSTUI", Toast.LENGTH_SHORT).show();
}catch(IOException e) {
Toast.makeText(v.getContext(), "NO I/O", Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
String cause = "Message: " + e.getMessage();
Toast.makeText(v.getContext(), cause, Toast.LENGTH_SHORT).show();
}
}
});
}
I've tryed also to use the code commented but it doesn't work;
This is the program that runs on the Server:
static void Main(string[] args)
{
string ip = Get_external_ip();
int port = 52301;
int max = 10;
IPAddress ipAddress = IPAddress.Parse("192.168.1.56");
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port); //setto i parametri del socket
Socket sockServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //creo il socket
Socket client;
Console.WriteLine(ip);
try
{
sockServer.Bind(localEndPoint);
sockServer.Listen(max);
while (true)
{
client = sockServer.Accept();
Console.WriteLine(client.RemoteEndPoint.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
private static string Get_external_ip()
{
try
{
WebClient client = new WebClient();
return client.DownloadString("http://icanhazip.com/").TrimEnd('\r', '\n');
}
catch (Exception e)
{
return e.Message;
}
}

First of all, use background Thread for network.
I will give you my working snippet. Try to apply it for your needs.
public class YourClass {
//Server socket variables
private ServerSocket serverSocket;
private DataOutputStream dataOutputStream;
private DataInputStream dataInputStream;
private Socket client;
....
private class SocketServerThread extends Thread {
private int port;
private SocketServerThread(int port) {
this.port = port;
}
#Override
public void run() {
dataInputStream = null;
dataOutputStream = null;
try {
serverSocket = new ServerSocket(port);
isSockedOpened = true;
client = serverSocket.accept(); //wait for client
isClientConnected = true;
Log.d(TAG, "Client connected: " + client.getInetAddress().getHostAddress());
dataInputStream = new DataInputStream(
client.getInputStream());
dataOutputStream = new DataOutputStream(
client.getOutputStream());
String messageFromClient;
while (isClientConnected) {
messageFromClient = dataInputStream.readLine();
handleIncomingMessage(messageFromClient);
}
}
} catch (IOException e) {
Log.e(TAG, e.getMessage());
} catch (NullPointerException e) {
Log.e(TAG, e.getMessage());
}
}
}
To open connection:
public void connect(int port) {
this.port = port;
Thread socketServerThread = new Thread(new SocketServerThread(port));
socketServerThread.start();
}
That's how you check if client connected;
public boolean isConnected() {
return serverSocket.isBound() || client.isConnected();
}
To disconnect:
public void disconnect(boolean needsGathering) {
if (isSockedOpened) {
try {
if (serverSocket != null) {
serverSocket.close();
}
if (dataOutputStream != null) {
dataOutputStream.close();
}
if (dataInputStream != null) {
dataInputStream.close();
}
if (client != null) {
client.close();
}
} catch (IOException e) {
Log.e(TAG, "Couldn't get I/O for the connection");
Log.e(TAG, e.getMessage());
}
} else {
Log.d(TAG, "Socket was not opened");
}
}
}

Related

can not connect to server after some time

Client :
public class TCPClientWrapper : IDisposable
{
private TcpClient tcpClient;
private readonly string address;
private readonly int port;
public TCPClientWrapper(string address, int port)
{
tcpClient = new TcpClient();
this.address = address;
this.port = port;
}
private void TryConnect()
{
tcpClient = new TcpClient();
tcpClient.SendTimeout = 15;
bool isConnected = false;
while (true)
{
try
{
Log.Info("TcpClient, Trying Connect");
tcpClient.Connect(IPAddress.Parse(address), port);
if (SocketConnected(tcpClient.Client))
{
Log.Info("TcpClient, Connected");
isConnected = true;
break;
}
}
catch (Exception e)
{
Log.Info("TcpClient, connection failed. Try to reconnect after 30 seconds, {0}", e.Message);
}
finally
{
if (!isConnected)
Thread.Sleep(30000);
}
}
}
public void SendMessage(string msg)
{
if (!SocketConnected(tcpClient.Client))
{
TryConnect();
}
byte[] buffer = Encoding.UTF8.GetBytes(msg);
tcpClient.Client.Send(buffer);
}
private bool SocketConnected(Socket s)
{
if (!s.Connected)
return false;
bool part1 = s.Poll(1000, SelectMode.SelectRead);
bool part2 = s.Available == 0;
return !(part1 && part2);
}
public void Dispose()
{
tcpClient.Close();
}
}
Server running as windows service:
public class TcpServer
{
private bool started;
private bool stopped;
private TcpListener tcpListener;
private static ManualResetEvent allDone = new ManualResetEvent(false);
public TcpServer(string url, int port)
{
tcpListener = new TcpListener(IPAddress.Parse(url), port);
}
[MethodImpl(MethodImplOptions.Synchronized)]
public void Run()
{
if (started) return;
stopped = false;
tcpListener.Start();
Task.Run(() =>
{
Log.Info("Server running");
while (!stopped)
{
allDone.Reset();
tcpListener.BeginAcceptSocket(AcceptCallback, tcpListener);
Log.Info("Accepting socket");
allDone.WaitOne();
}
});
Log.Info("Ping server started");
started = true;
}
[MethodImpl(MethodImplOptions.Synchronized)]
public void Stop()
{
if (!started) return;
stopped = true;
tcpListener.Stop();
started = false;
Log.Info("Ping server stopped");
}
private void AcceptCallback(IAsyncResult result)
{
try
{
allDone.Set();
if (stopped) return;
Log.Info("Socket accepted");
var listener = (TcpListener)result.AsyncState;
var socket = listener.EndAcceptSocket(result);
Log.Info("Process socket");
ProcessSocket(socket);
}
catch (Exception e)
{
Log.Info("Error accepting callback. {0}", e.Message);
}
}
private void ProcessSocket(Socket socket)
{
try
{
byte[] buffer = new byte[256];
while (!stopped && socket.Receive(buffer) != 0)
{
var msg = Encoding.UTF8.GetString(buffer);
Console.WriteLine(msg);
}
}
catch (Exception e)
{
socket.Close();
Log.Info("Socket closed:{0}", !socket.Connected);
}
}
}
The server is configured in such a way that request to server processed on one IP xxx.xx.xxx.135:5050 and response from server given from xxx.xx.xxx.134:5050
The client works fine for some period of time, but after i get the following error on client side:
A connection attempt failed because the connected party did not
properly respond after a period of time, or established connection
failed because connected host has failed to respond
xxx.xx.xxx.135:5050
What is the reason that the client can't connect to server ?
Check firewall settings on production server
Check whether IP white listing is required
Antivirus might be blocking the request
If no luck, install Advanced REST Client tool on Chrome and manually
test the request
https://forums.asp.net/t/2138734.aspx?A+connection+attempt+failed+because+the+connected+party+did+not+properly+respond+after+a+period+of+time

Android Video Streaming Using DatagramSocket setPreviewCallback

I've made an application that obeys UDP using Datagram Socket in android. I'm trying to use Camera's setPreviewCallback function to send bytes to a (c#) client, using Datagram Socket;
But,
The problem is : it throws an exception "The datagram was too big to fit the specified buffer,so truncated" and no bytes are received on client.
I've changed the size of buffer to different values but none work. Now :
Is Datagram approach is right?
What alternatives/approach I'd use to achieve the task?
What's the ideal solution for this?
Android Server :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
videoView = (VideoView) findViewById(R.id.videoView1);
start = (Button)findViewById(R.id.start);
stop = (Button)findViewById(R.id.stop);
setTitle(GetCurrentIP());
mainList = new LinkedList<byte[]>();
secondaryList = new LinkedList<byte[]>();
mCam = null;
mCam = Camera.open();
if (mCam == null) {
Msg("Camera is null");
} else {
if (!Bind()) {
Msg("Bind Error.");
} else {
Msg("Bound Success.");
start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mCam.setPreviewDisplay(videoView.getHolder());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
Msg(e1.getMessage());
}
mCam.setPreviewCallback(new PreviewCallback() {
#Override
public void onPreviewFrame(byte[] data, Camera camera) {
// TODO Auto-generated method stub
DatagramPacket pack;
try {
pack = new DatagramPacket(data, data.length, InetAddress.getByName(clientIP), clientPort);
me.send(pack);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Msg(e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Msg(e.getMessage());
}
}
});
mCam.startPreview();
}
});
}
}
}
private boolean Bind(){
try {
me = new DatagramSocket(MY_PORT);
return true;
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Msg(e.getMessage());
}
return false;
}
private String GetCurrentIP(){
WifiManager wifiMgr = (WifiManager) getSystemService(WIFI_SERVICE);
return Formatter.formatIpAddress(wifiMgr.getConnectionInfo().getIpAddress());
}
public void Msg(String msg){
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
Log.v(">>>>>", msg);
}
}
C# client :
public partial class Form1 : Form
{
const int MY_PORT = 55566;
IPAddress MY_IP;
Thread Receiver;
Socket me;
EndPoint myEndPoint;
EndPoint serverEndPoint;
byte[] buffer;
public Form1()
{
InitializeComponent();
}
private IPAddress GetCurrentIPAddress()
{
IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());
var selectedIPs = from ip in ips
where ip.AddressFamily == AddressFamily.InterNetwork
select ip;
return selectedIPs.First();
}
private bool Bind()
{
try
{
myEndPoint = new IPEndPoint(MY_IP, MY_PORT);
me.Bind(myEndPoint);
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return false;
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
MY_IP = GetCurrentIPAddress();
this.Text = MY_IP.ToString()+":"+MY_PORT;
me = new Socket
(
AddressFamily.InterNetwork,
SocketType.Dgram,
ProtocolType.Udp
);
if (!Bind())
Task.Run(()=> MessageBox.Show("Bind() error."));
else
Task.Run(() => MessageBox.Show("Bind success."));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//private void AddToListBox(String msg)
//{
// this.Invoke((Action)delegate() { this.listBox1.Items.Add((this.listBox1.Items.Count+1)+" : "+msg); });
//}
private void buttonStart_Click(object sender, EventArgs e)
{
serverEndPoint = new IPEndPoint(IPAddress.Parse(textBoxmyIP.Text), int.Parse(textBoxmyPort.Text));
Receiver = new Thread(new ThreadStart(Receive));
Receiver.Start();
}
private Image ByteToImage(byte[] bytes)
{
MemoryStream ms = new MemoryStream(bytes);
return Image.FromStream(ms);
}
private void Receive()
{
while (true)
{
buffer = new byte[100];
int nobs = me.ReceiveFrom(buffer, ref serverEndPoint);
if (nobs>0)
{
Task.Run(() => MessageBox.Show("Bytes received"));
//AddToListBox(Encoding.Default.GetString(buffer));
//AddToPictureBox(buffer);
}
Thread.Sleep(100);
}
}
private void AddToPictureBox(byte[] buffer)
{
this.BeginInvoke
(
(Action)
delegate()
{
pictureBox1.Image = ByteToImage(buffer);
}
);
}
}

C# Form. Changing a Client / Server chat room so clients can speak with one another

This question has probably been asked before.
Okay so I am still learning how to program with sockets but I was wondering how you could change the client / server so that clients can talk amongst themselves as well as the server talking to the clients like an administrator.
I have found various things on Handle Clients but these were for Console Apps and not C# Windows Forms, I tried to covert them but with no luck.
This is my server code so far.
namespace Socket_Server
{
public partial class Form1 : Form
{
const int MAX_CLIENTS = 30;
public AsyncCallback pfnWorkerCallBack;
private Socket m_mainSocket;
private Socket[] m_workerSocket = new Socket[30];
private int m_clientCount = 20;
string readData = null;
public Form1()
{
InitializeComponent();
textBoxIP.Text = GetIP();
}
private void buttonStartListen_Click(object sender, EventArgs e)
{
try
{
if (textBoxPort.Text == "")
{
MessageBox.Show("Please enter a Port Number");
return;
}
string portStr = textBoxPort.Text;
int port = System.Convert.ToInt32(portStr);.
m_mainSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, port);
m_mainSocket.Bind(ipLocal);
m_mainSocket.Listen(4);
m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
UpdateControls(true);
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}
private void UpdateControls(bool listening)
{
buttonStartListen.Enabled = !listening;
buttonStopListen.Enabled = listening;
}
public void OnClientConnect(IAsyncResult asyn)
{
try
{
m_workerSocket[m_clientCount] = m_mainSocket.EndAccept(asyn);
WaitForData(m_workerSocket[m_clientCount]);
++m_clientCount;
String str = String.Format("Client # {0} connected", m_clientCount);
Invoke(new Action(() =>textBoxMsg.Clear()));
Invoke(new Action(() =>textBoxMsg.AppendText(str)));
m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
}
catch (ObjectDisposedException)
{
System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}
public class SocketPacket
{
public System.Net.Sockets.Socket m_currentSocket;
public byte[] dataBuffer = new byte[1024];
}
public void WaitForData(System.Net.Sockets.Socket soc)
{
try
{
if (pfnWorkerCallBack == null)
{
pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
}
SocketPacket theSocPkt = new SocketPacket();
theSocPkt.m_currentSocket = soc;// could be this one!!!
soc.BeginReceive(theSocPkt.dataBuffer, 0,
theSocPkt.dataBuffer.Length,
SocketFlags.None,
pfnWorkerCallBack,
theSocPkt);
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}
public void OnDataReceived(IAsyncResult asyn)
{
try
{
SocketPacket socketData = (SocketPacket)asyn.AsyncState;
int iRx = 0;
iRx = socketData.m_currentSocket.EndReceive(asyn);
char[] chars = new char[iRx + 1];
System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(socketData.dataBuffer,
0, iRx, chars, 0);
System.String szData = new System.String(chars);
Invoke(new Action(() => richTextBoxSendMsg.AppendText(szData)));
Invoke(new Action(() => richTextBoxSendMsg.AppendText(Environment.NewLine)));
WaitForData(socketData.m_currentSocket);
}
catch (ObjectDisposedException)
{
System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}
private void buttonSendMsg_Click(object sender, EventArgs e)
{
try
{
Object objData = txtBoxType.Text;
byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString());
for (int i = 0; i < m_clientCount; i++)
{
if (m_workerSocket[i] != null)
{
if (m_workerSocket[i].Connected)
{
m_workerSocket[i].Send(byData);
txtBoxType.Clear();
}
}
}
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}
private void buttonStopListen_Click(object sender, EventArgs e)
{
CloseSockets();
UpdateControls(false);
}
String GetIP()
{
String strHostName = Dns.GetHostName();
IPHostEntry iphostentry = Dns.GetHostEntry(strHostName);
String IPStr = "";
foreach (IPAddress ipaddress in iphostentry.AddressList)
{
if (ipaddress.IsIPv6LinkLocal == false)
{
IPStr = IPStr + ipaddress.ToString();
return IPStr;
}
}
return IPStr;
}
private void buttonClose_Click(object sender, EventArgs e)
{
CloseSockets();
Close();
}
void CloseSockets()
{
if (m_mainSocket != null)
{
m_mainSocket.Close();
}
for (int i = 0; i < m_clientCount; i++)
{
if (m_workerSocket[i] != null)
{
m_workerSocket[i].Close();
m_workerSocket[i] = null;
}
}
}
}
}
Thank you in advance.

Android Socket Listener Only Runs Once

I have an Android application that is currently using a Socket Listener to listen for incoming connections from a C# application. I am able to get the C# application to send a string to the Android application, but the Socket Listener only seems to accept/execute the necessary code to write the information out only once, but continues to accept incoming connection requests from the C# application.
I have searched through Stackoverflow and spent plenty of time on Google, but can't seem to nail down the exact cause for this issue. Below is my code.
Android Code
public class ScoringActivity extends Activity
{
InputStream is;
private String ipAddress = "";
ProgressDialog progress;
private TextView serverStatus;
// DEFAULT IP
public static String SERVERIP = "10.0.2.2";
// DESIGNATE A PORT
public static final int SERVERPORT = 6000;
private Handler handler = new Handler();
private ServerSocket serverSocket;
#Override
protected void onCreate(Bundle savedInstanceState)
{
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
super.onCreate(savedInstanceState);
setContentView(R.layout.scoring);
Intent intent= getIntent();
ipAddress = intent.getStringExtra("ipAddress");
setProgressBarIndeterminateVisibility(false);
Thread fst = new Thread(new ServerThread());
fst.start();
}
public class ServerThread implements Runnable
{
public void run()
{
try
{
if (SERVERIP != null)
{
handler.post(new Runnable()
{
#Override
public void run()
{
Log.d("Listening on IP: ", SERVERIP + " " + SERVERPORT);
}
});
serverSocket = new ServerSocket(SERVERPORT);
while (true)
{
// LISTEN FOR INCOMING CLIENTS
Socket client = serverSocket.accept();
handler.post(new Runnable()
{
#Override
public void run()
{
Log.d("Connected.","Connected.");
}
});
try
{
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line = null;
while ((line = in.readLine()) != null)
{
Log.d("ServerActivity", line);
handler.post(new Runnable()
{
#Override
public void run()
{
Log.d("In the run method", "in the run method");
}
});
}
in.close();
break;
} catch (Exception e)
{
handler.post(new Runnable()
{
#Override
public void run()
{
Log.d("Oops. Connection interrupted. Please reconnect your phones.","Oops. Connection interrupted. Please reconnect your phones.");
}
});
e.printStackTrace();
}
}
} else
{
handler.post(new Runnable()
{
#Override
public void run()
{
Log.d("Couldn't detect internet connection.","Couldn't detect internet connection.");
}
});
}
} catch (Exception e)
{
handler.post(new Runnable()
{
#Override
public void run()
{
Log.d("Error","Error");
}
});
e.printStackTrace();
}
}
}
}
C# Code
//ProcessSqlFiles();
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
if (!clientSocket.Connected)
clientSocket.Connect(IPAddress.Parse("127.0.0.1"), 8080);
clientSocket.Send(Encoding.UTF8.GetBytes("Test Input"));
clientSocket.Close();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
You're breaking out of the loop:
}
in.close();
break;
Remove the break statement. I think what you may want is continue assuming you want to go back to the start of the infinite loop.

how to translate this (see the code below )to C#?

how to translate this to C#
import java.io.*;
import java.net.*;
class SimpleServer
{
private static SimpleServer server;
ServerSocket socket;
Socket incoming;
BufferedReader readerIn;
PrintStream printOut;
public static void main(String[] args)
{
int port = 8080;
try
{
port = Integer.parseInt(args[0]);
}
catch (ArrayIndexOutOfBoundsException e)
{
// Catch exception and keep going.
}
server = new SimpleServer(port);
}
private SimpleServer(int port)
{
System.out.println(">> Starting SimpleServer");
try
{
socket = new ServerSocket(port);
incoming = socket.accept();
readerIn = new BufferedReader(new InputStreamReader(incoming.getInputStream()));
printOut = new PrintStream(incoming.getOutputStream());
printOut.println("Enter EXIT to exit.\r");
out("Enter EXIT to exit.\r");
boolean done = false;
while (!done)
{
String str = readerIn.readLine();
if (str == null)
{
done = true;
}
else
{
out("Echo: " + str + "\r");
if(str.trim().equals("EXIT"))
{
done = true;
}
}
incoming.close();
}
}
catch (Exception e)
{
System.out.println(e);
}
}
private void out(String str)
{
printOut.println(str);
System.out.println(str);
}
}
Something like this should work:
using System;
using System.IO;
using System.Net.Sockets;
using System.Text;
namespace Server
{
internal class SimpleServer
{
private static SimpleServer server;
private readonly TcpListener socket;
private SimpleServer(int port)
{
Console.WriteLine(">> Starting SimpleServer");
socket = new TcpListener(port);
socket.Start();
}
private void DoJob()
{
try
{
bool done = false;
while (!done)
{
TcpClient client = socket.AcceptTcpClient();
NetworkStream stream = client.GetStream();
var reader = new StreamReader(stream, Encoding.UTF8);
String str = reader.ReadLine();
if (str == null)
{
done = true;
}
else
{
printOut(str, stream);
if (str.Trim() == "EXIT")
{
done = true;
}
}
client.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
public static void main(String[] args)
{
int port = 8080;
try
{
port = Int32.Parse(args[0]);
}
catch (Exception e)
{
// Catch exception and keep going.
}
server = new SimpleServer(port);
server.DoJob();
}
private void printOut(String str, Stream stream)
{
byte[] bytes = Encoding.UTF8.GetBytes("Echo: " + str + "\r\n");
stream.Write(bytes, 0, bytes.Length);
Console.WriteLine(str);
}
}
}
edit: but be careful with encoding
Take a look at the TCPListener sample on MSDN. It's very similar to what you're trying to do above, and porting the few differences over should be easy.

Categories