Send data from android to C# - c#

I want to send data from android to C#. C# is server. Android is client
I connect my computer to mobile's hotspot but i receive this error:
failed to connect to 192.168.1.15(port 4444):connect failed:ENETUNREACH(Network is unreachable
Here is the java code:
public class MainActivity extends Activity {
//TextView tv=(TextView) findViewById(R.id.textView2);
EditText edittext1;
private TCPClient mTcpClient;
private Button btnIP;
private TextView txt1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt1 = (TextView) findViewById(R.id.textView1);
final EditText editText = (EditText)findViewById(R.id.edit_message);
edittext1=(EditText) findViewById(R.id.editText1);
btnIP=(Button) findViewById(R.id.button1);
Button bt2=(Button) findViewById(R.id.button2);
bt2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
txt1.setText(TCPClient.log) ;
}
});
Button send = (Button)findViewById(R.id.send_button);
// connect to the server
new connectTask().execute("");
btnIP.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
TCPClient.SERVERIP=edittext1.getText().toString();
new connectTask().execute("");
}
});
send.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View view) {
String message = editText.getText().toString();
//sends the message to the server
if (mTcpClient != null)
{
mTcpClient.sendMessage(message);
}
editText.setText("");
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class connectTask extends AsyncTask<String,String,TCPClient>
{
#Override
protected TCPClient doInBackground(String... message)
{
mTcpClient = new TCPClient(new OnMessageReceived()
{
#Override public void messageReceived(String message)
{
publishProgress(message);
}
});
Looper.prepare();
mTcpClient.run();
return null;
}
#Override
protected void onProgressUpdate(String... values)
{
super.onProgressUpdate(values);
}
}
public static class TCPClient
{
private String serverMessage;
public static String SERVERIP = "192.168.1.15";
public static final int SERVERPORT = 4444;
private OnMessageReceived mMessageListener = null;
public static String log="";
private boolean mRun = false;
PrintWriter out;
BufferedReader in;
DataOutputStream dataOutputStream = null;
//OutputStream os;
public TCPClient(OnMessageReceived listener)
{
mMessageListener = listener;
}
public void sendMessage(String message)
{
if (out != null && !out.checkError())
{
/* String toSend = "a"; byte[] toSendBytes = toSend.getBytes();
int toSendLen = toSendBytes.length; byte[] toSendLenBytes = new byte[4];
toSendLenBytes[0] = (byte)(toSendLen & 0xff); toSendLenBytes[1] = (byte)((toSendLen >> 8) & 0xff); toSendLenBytes[2] = (byte)((toSendLen >> 16) & 0xff); toSendLenBytes[3] = (byte)((toSendLen >> 24) & 0xff); try { os.write(toSendLenBytes); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { os.write(toSendBytes);
} catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } */
out.print(message);
out.flush();
}
}
public void stopClient()
{
mRun = false;
}
public void run()
{
// TextView tv=(TextView) findViewById(R.id.textView2);
//tv.setText(tv.getText()+"\n"+ "run");
mRun = true;
try
{
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
Log.e("TCP Client", "C: Connecting...");
log="C: Connecting...";
//Toast.makeText(MainActivity.this, "Connecting", Toast.LENGTH_SHORT).show();
//tv.setText(tv.getText()+"\n"+ "Connecting");
//tv.setText(tv.getText()+"\n"+ "Connecting...");
Socket socket = new Socket(serverAddr, SERVERPORT);
/// //os = socket.getOutputStream();
if(socket.isBound())
{
Log.i("SOCKET", "Socket: Connected");
log="Connected";
//tv.setText(tv.getText()+"\n"+ "Connected");
//Toast.makeText(MainActivity.this, "Connected", Toast.LENGTH_SHORT).show();
//tv.setText(tv.getText()+"\n"+ "Connected");
}
else{
Log.e("SOCKET", "Socket: Not Connected");
log="Not Connected";
// tv.setText(tv.getText()+"\n"+ "not Connected");
//Toast.makeText(MainActivity.this, "not Connected", Toast.LENGTH_SHORT).show();
//tv.setText(tv.getText()+"\n"+ " Not Connected");
} try {
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
//out.println(new char[]{'h','e'});
//out.flush();
/* dataOutputStream = new DataOutputStream(socket.getOutputStream()); byte[] bytes = new byte[] {1};
* dataOutputStream.write(bytes, 0, bytes.length); */
Log.e("TCP Client", "C: Sent.");
log=" Sent";
Log.e("TCP Client", "C: Done.");
log=" Done";
if(out.checkError())
{
Log.e("PrintWriter", "CheckError");
}
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (mRun)
{
serverMessage = in.readLine();
if (serverMessage != null && mMessageListener != null)
{
mMessageListener.messageReceived(serverMessage);
}
serverMessage = null;
}
Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'");
} catch (Exception e) { Log.e("TCP", "S: Error", e); }
finally { socket.close(); }
}
catch (Exception e) { Log.e("TCP", "C: Error", e);
log=e.getMessage();
//tv.setText(tv.getText()+"\n"+ e.getMessage());
}
}
}
}
C# code:
class Program
{
static private IPAddress getLocalIPAddress()
{
IPHostEntry host;
//string localIP = "";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
// localIP = ip.ToString();
return ip;
//break;
}
}
// return localIP;
return null;
}
static void Main(string[] args)
{
int recv;
byte[] data = new byte[2048];
IPEndPoint ipep = new IPEndPoint(getLocalIPAddress(), 4444);
Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
newsock.Bind(ipep);
newsock.Listen(10);
Console.WriteLine("Waiting for a client...");
Socket client = newsock.Accept();
IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
Console.WriteLine("Connected with {0} at port{1}", clientep.Address, clientep.Port);
string welcome = "Welcome to my test server";
data = Encoding.ASCII.GetBytes(welcome);
client.Send(data, data.Length, SocketFlags.None);
while (true)
{
data = new byte[1024];
recv = client.Receive(data);
if (recv == 0)
break;
Console.WriteLine(Encoding.ASCII.GetString(data, 0,
recv));
client.Send(data, recv, SocketFlags.None);
}
Console.WriteLine("Disconnected from{0}", clientep.Address);
client.Close();
newsock.Close();
}
}

Related

TCP socket timeout

I wrote C# program that server sends data from Server to Client only.
Problem is that time between it sends data is changable ( max 5min)
and that causes sometimes connection to timeout.
When I send data every 3sec then none of them timeouts.
But if message send after 5min then there is problem on Client to recieve it.
I made timeout feature that both Client and Server has. After timeout every reconnects:
public class TimerControl
{
private System.Timers.Timer timeoutTimer = null;
public void initTimeout(int timeMS, System.Timers.ElapsedEventHandler funct)
{
timeoutTimer = new System.Timers.Timer();
timeoutTimer.Interval = timeMS; //MS
timeoutTimer.Elapsed += funct;
timeoutTimer.AutoReset = true;
setTimeoutTimer(false);
}
public void setTimeoutTimer(bool state)
{
if (timeoutTimer != null)
{
timeoutTimer.Stop();
timeoutTimer.Enabled = state;
if (state) timeoutTimer.Start();
}
}
public void resetTimeoutTimer()
{
if (timeoutTimer != null && timeoutTimer.Enabled)
{
timeoutTimer.Stop();
timeoutTimer.Start();
}
}
}
that has not solved the trouble.
What should I do to make it work correct and not timeout after some time?
Server:
public class TCPserver :TCPunit
{
private int TIMEOUT_MS = 5000;
Socket serverListener = null;
Queue<string> dataQueued = null;
bool isConnectedForced = false;
public TCPserver()
{
dataQueued = new Queue<string>();
initTimeout(TIMEOUT_MS, reconnect);
}
public void sendDataToClient(string message)
{
dataQueued.Enqueue(message + Environment.NewLine);
if(isConnectedForced) startListening();
if (dataQueued.Count > 0) setTimeoutTimer(true);
}
public bool connect(string adress)
{
this.thisUnitAdress = adress;
isConnectedForced = true;
loopedConnect();
startListening();
return true;
}
public bool disconnect()
{
isConnectedForced = false;
loopedDisconnect();
return true;
}
private bool loopedConnect()
{
try
{
IPAddress ipAddress = IPAddress.Parse(this.thisUnitAdress);
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);
if (serverListener != null) loopedDisconnect();
serverListener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
serverListener.Bind(localEndPoint);
Console.WriteLine("SERVER connected to: " + this.thisUnitAdress + " port : " + port.ToString());
return true;
}
catch (Exception ex)
{
Console.WriteLine("!!! SERVER connect");
setTimeoutTimer(true);
return false;
}
}
private bool loopedDisconnect()
{
setTimeoutTimer(false);
if (serverListener != null)
{
if (serverListener.Connected) serverListener.Shutdown(SocketShutdown.Both);
serverListener.Close();
Console.WriteLine("SERVER CLOSED!");
serverListener = null;
}
return true;
}
private void reconnect(Object source, System.Timers.ElapsedEventArgs e)
{
if (isConnectedForced)
{
Console.WriteLine("SERVER RECONNECT!!!");
loopedDisconnect();
loopedConnect();
if (dataQueued.Count > 0) setTimeoutTimer(true);
else setTimeoutTimer(false);
}
else
{
setTimeoutTimer(false);
}
}
private void startListening()
{
try
{
serverListener.Listen(100);
Console.WriteLine("SERVER Waiting for a connection...");
serverListener.BeginAccept(new AsyncCallback(AcceptCallback), serverListener);
setTimeoutTimer(true);
}
catch (Exception ex)
{
Console.WriteLine("!!! SERVER sendingLOOP");
setTimeoutTimer(true);
}
}
private void AcceptCallback(IAsyncResult ar)
{
try
{
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
//HERE SEND
while (dataQueued.Count > 0)
{
string data = dataQueued.Dequeue();
byte[] byteData = Encoding.ASCII.GetBytes(data);
handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
}
//handler.Shutdown(SocketShutdown.Both);
//handler.Close();
setTimeoutTimer(false);
}
catch (Exception ex)
{
Console.WriteLine("!!! SERVER AcceptCallback");
setTimeoutTimer(true);
}
}
private void SendCallback(IAsyncResult ar)
{
try
{
((Socket)ar.AsyncState).EndSend(ar);
}
catch(Exception ex)
{
Console.WriteLine("!!! SERVER SendCallback");
setTimeoutTimer(true);
}
}
}
Client:
public class TCPclient : TCPunit
{
private int TIMEOUT_MS = 5000;
Socket client;
IPEndPoint remoteEP;
bool isConnecting = false;
bool isRecieving = false; // TELS IF PROGRAM SHOULD LOOK FOR SERVER ALL TIME
Action<string> afterRecieveAction = null ; // To print to GUI
public TCPclient()
{
initTimeout(TIMEOUT_MS, reconnect);
}
public void assignAfterRecieveAction(Action<string> action)
{
this.afterRecieveAction = action;
}
public bool connect(string adress)
{
thisUnitAdress = adress;
loopedConnect();
return true;
}
public bool disconnect()
{
isRecieving = false;
isConnecting = false;
loopedDisconnect();
return true;
}
private bool loopedConnect()
{
IPAddress ipAddress = IPAddress.Parse(this.thisUnitAdress);
remoteEP = new IPEndPoint(ipAddress, port);
client = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
setTimeoutTimer(true);
isRecieving = true;
StartClientListening();
return true;
}
private bool loopedDisconnect()
{
if (client != null)
{
if (client.Connected) client.Shutdown(SocketShutdown.Both);
client.Close();
Console.WriteLine("CLIENT CLOSED!");
client = null;
}
return true;
}
private void reconnect(Object source, System.Timers.ElapsedEventArgs e)
{
if (isRecieving)
{
Console.WriteLine("CLIENT RECONNECT!!!");
if (isConnecting) loopedDisconnect();
isRecieving = true;
loopedConnect();
}
}
private void StartClientListening()
{
try
{
if (isRecieving)
{
client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback) , client);
isConnecting = true;
Console.WriteLine("CLIENT listens to: " + thisUnitAdress + " port : " + port.ToString());
}
}
catch (System.Net.Sockets.SocketException ex)
{
Console.WriteLine("CLIENT StartClientListening");
}
catch (Exception ex)
{
Console.WriteLine("!!! CLIENT StartClientListening2");
if (isRecieving) setTimeoutTimer(true);
}
}
private void ConnectCallback(IAsyncResult ar)
{
try
{
client.EndConnect(ar);
Console.WriteLine("CLIENT connected to {0}", client.RemoteEndPoint.ToString());
StateObject state = new StateObject();
state.workSocket = client;
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state); ;
}
catch (Exception e)
{
Console.WriteLine("!!! CLIENT ConnectCallback");
if (isRecieving) setTimeoutTimer(true);
}
}
private void ReceiveCallback(IAsyncResult ar)
{
try
{
StateObject state = (StateObject)ar.AsyncState;
Socket client = state.workSocket;
int bytesRead = client.EndReceive(ar);
if (bytesRead > 0)
{
String response = Encoding.ASCII.GetString(state.buffer);
if (afterRecieveAction != null) afterRecieveAction(response);
resetTimeoutTimer();
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
}
}
catch(System.Net.Sockets.SocketException ex)
{
Console.WriteLine("!!! CLIENT ReceiveCallback");
if (isRecieving) setTimeoutTimer(true);
}
catch(Exception ex)
{
Console.WriteLine("!!! CLIENT ReceiveCallback2");
if (isRecieving) setTimeoutTimer(true);
}
}
}
How to make async Server-Client to work without timeouts?
Best regards,
Chris
You should use socket_set_option to parameter this

How to implement Socket server that accept more message

I want to send at real time some data from Android application to server.
So I'm building a simple socket Server in c# like this:
class Program
{
private Socket listener;
static void Main(string[] args)
{
Program p = new Program();
p.socketServer();
}
public void socketServer()
{
int MAXBUFFER = 1024;
Console.WriteLine("SOCKET STARTED");
listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(new IPEndPoint(IPAddress.Any, 8080));
listener.Listen(10);
while (true)
{
Console.WriteLine("WAITING CONNECTION");
Socket socket = listener.Accept();
string receivedMessage = string.Empty;
while (true)
{
byte[] receivedBytes = new byte[MAXBUFFER];
int numBytes = socket.Receive(receivedBytes);
receivedMessage += Encoding.ASCII.GetString(receivedBytes, 0, numBytes);
if (receivedMessage.IndexOf("\n") > -1)
{
Console.WriteLine("MESSAGE FROM CLIENT: {0}", receivedMessage);
//break;
}
}
Console.WriteLine("MESSAGE FROM CLIENT: {0}", receivedMessage);
string replyMessage = "MESSAGE RECEIVED";
byte[] replyBytes = Encoding.ASCII.GetBytes(replyMessage);
}
}
public void shutdownServer()
{
listener.Shutdown(SocketShutdown.Both);
listener.Close();
}
}
And I'm building this class to send data from Android application:
public class TcpClient {
public static final String SERVER_IP = "192.168.110.50"; // computer IP address
public static final int SERVER_PORT = 8080;
private String mServerMessage;
private OnMessageReceived mMessageListener = null;
private boolean mRun = false;
private PrintWriter mBufferOut;
private BufferedReader mBufferIn;
private Socket socket;
/**
* Constructor of the class. OnMessagedReceived listens for the messages received from server
*/
public TcpClient(OnMessageReceived listener) {
mMessageListener = listener;
}
/**
* Sends the message entered by client to the server
*
* #param message text entered by client
*/
public void sendMessage(String message) {
socket.isConnected();
if (mBufferOut != null /*&& !mBufferOut.checkError()*/) {
mBufferOut.println(message);
}
}
/**
* Close the connection and release the members
*/
public void stopClient() {
Log.i("Debug", "stopClient");
// send mesage that we are closing the connection
//sendMessage(Constants.CLOSED_CONNECTION + "Kazy");
mRun = false;
if (mBufferOut != null) {
mBufferOut.flush();
mBufferOut.close();
}
mMessageListener = null;
mBufferIn = null;
mBufferOut = null;
mServerMessage = null;
}
public void run() {
mRun = true;
try {
//here you must put your computer's IP address.
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
//create a socket to make the connection with the server
socket = new Socket(SERVER_IP, SERVER_PORT);
//socket.connect(socket.getRemoteSocketAddress());
socket.isConnected();
try {
Log.i("Debug", "inside try catch");
mBufferOut = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
} catch (Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
}
}
public interface OnMessageReceived {
public void messageReceived(String message);
}
}
And in the MainActivity I use this code:
tcpClient = new TcpClient(new TcpClient.OnMessageReceived() {
#Override
//here the messageReceived method is implemented
public void messageReceived(String message) {
//this method calls the onProgressUpdate
//publishProgress(message);
}
});
tcpClient.run();
After connect to server i user this code to send message:
for(int i=0; i<10; i++){
tcpClient.sendMessage("test " + i);
}
The problem is that only the first message arrive to the server. I think that the problem is on the socket server that lost the connection with the client.

C# async SocketException while binding

I am working on a client-server application on C# using async sockets. As I listen for connections, I keep getting this error
An unhandled exception of type 'System.Net.Sockets.SocketException'
occurred in System.dll
Additional information: Only one usage of each socket address (protocol/network address/port) is normally permitted
This is the line where this exception happens:
_listener.Bind(new IPEndPoint(0, port));
The code is under Listener.Start(int port). In the main program, here's how I call the method:
void btnListen_Click(object sender, EventArgs e)
{
_listener = new Listener();
_listener.Accepted += new Listener.SocketAcceptedHandler(listener_Accepted);
_listener.Start(8192);
}
I am testing both the client and server applications in my PC.
Here's the Listener class.
namespace serverPC
{
class Listener
{
public delegate void SocketAcceptedHandler(Socket e);
public event SocketAcceptedHandler Accepted;
Socket _listener;
public int Port;
public bool Running
{
get;
private set;
}
public Listener() {Port = 0;}
public void Start(int port)
{
if (Running)
return;
_listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_listener.Bind(new IPEndPoint(0, port)); // This is where the SocketException error occurs
_listener.Listen(0);
_listener.BeginAccept(acceptedCallback, null);
Running = true;
}
public void Stop()
{
if (!Running)
return;
_listener.Close();
Running = false;
}
void acceptedCallback(IAsyncResult ar)
{
try
{
Socket s = _listener.EndAccept(ar);
if (Accepted != null)
{
Accepted(s);
}
}
catch
{
}
if (Running)
{
try
{
_listener.BeginAccept(acceptedCallback, null);
}
catch
{
}
}
}
}
}
Here's the Client class.
namespace serverPC
{
struct ReceiveBuffer
{
public const int BUFFER_SIZE = 1024;
public byte[] Buffer;
public int ToReceive;
public MemoryStream BufStream;
public ReceiveBuffer(int toRec)
{
Buffer = new byte[BUFFER_SIZE];
ToReceive = toRec;
BufStream = new MemoryStream(toRec);
}
public void Dispose()
{
Buffer = null;
ToReceive = 0;
Close();
if (BufStream != null)
BufStream.Dispose();
}
public void Close()
{
if (BufStream != null && BufStream.CanWrite)
{
BufStream.Close();
}
}
}
class Client
{
byte[] lenBuffer;
ReceiveBuffer buffer;
Socket _socket;
public IPEndPoint EndPoint
{
get
{
if (_socket != null && _socket.Connected)
{
return (IPEndPoint)_socket.RemoteEndPoint;
}
return new IPEndPoint(IPAddress.None, 0);
}
}
public delegate void DisconnectedEventHandler(Client sender);
public event DisconnectedEventHandler Disconnected;
public delegate void DataReceivedEventHandler(Client sender, ReceiveBuffer e);
public event DataReceivedEventHandler DataReceived;
public Client(Socket s)
{
_socket = s;
lenBuffer = new byte[4];
}
public void Close()
{
if (_socket != null)
{
_socket.Disconnect(false);
_socket.Close();
}
buffer.Dispose();
_socket = null;
lenBuffer = null;
Disconnected = null;
DataReceived = null;
}
public void ReceiveAsync()
{
_socket.BeginReceive(lenBuffer, 0, lenBuffer.Length, SocketFlags.None, receiveCallback, null);
}
void receiveCallback(IAsyncResult ar)
{
try
{
int rec = _socket.EndReceive(ar);
if (rec == 0)
{
if (Disconnected != null)
{
Disconnected(this);
return;
}
if (rec != 4)
{
throw new Exception();
}
}
}
catch (SocketException se)
{
switch (se.SocketErrorCode)
{
case SocketError.ConnectionAborted:
case SocketError.ConnectionReset:
if (Disconnected != null)
{
Disconnected(this);
return;
}
break;
}
}
catch (ObjectDisposedException)
{
return;
}
catch (NullReferenceException)
{
return;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return;
}
buffer = new ReceiveBuffer(BitConverter.ToInt32(lenBuffer, 0));
_socket.BeginReceive(buffer.Buffer, 0, buffer.Buffer.Length, SocketFlags.None, receivePacketCallback, null);
}
void receivePacketCallback(IAsyncResult ar)
{
int rec = _socket.EndReceive(ar);
if (rec <= 0)
{
return;
}
buffer.BufStream.Write(buffer.Buffer, 0, rec);
buffer.ToReceive -= rec;
if(buffer.ToReceive > 0)
{
Array.Clear(buffer.Buffer, 0, buffer.Buffer.Length);
_socket.BeginReceive(buffer.Buffer, 0, buffer.Buffer.Length, SocketFlags.None, receivePacketCallback, null);
return;
}
if (DataReceived != null)
{
buffer.BufStream.Position = 0;
DataReceived(this, buffer);
}
buffer.Dispose();
ReceiveAsync();
}
}
}
Why do I get the SocketException error? Any help is appreciated. Thanks!
So the obvious things to check - Something is already listening on port 8192 or there's some other reason why your machine would reject your program opening that port (firewalls, etc).
The other problem is while you are blocking binding twice with the "Running" check, you're only doing that for the instance of listener - hitting the button will create a whole new listener and attempt to have it listen on port 8192 - which since you already have a listener bound there, will fail with that exception.

Android TCP communication error

I am very new to Android Programming .
My code in android is as follows
public class AndroidClient extends Activity {
EditText textOut;
TextView textIn;
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_client);
textOut = (EditText)findViewById(R.id.textout);
Button buttonSend = (Button)findViewById(R.id.send);
textIn = (TextView)findViewById(R.id.textin);
buttonSend.setOnClickListener(buttonSendOnClickListener);
}
Button.OnClickListener buttonSendOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new BackgroundDataTask().execute("");
}};
public class BackgroundDataTask extends AsyncTask<String,String,String> {
private Exception ex;
#Override
protected String doInBackground(String... urls) {
try {
socket = new Socket("10.20.50.68", 8888);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(textOut.getText().toString());
textIn.setText(dataInputStream.readUTF());
socket = serverSocket.accept();
textIn.setText(socket.getInetAddress().toString());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return "";
}
}
}
I have a server in C# Code
The code listens to the port and writes the output
However this only works for the first time when I type in the text and click Send the code is received at Server end and I can see the ouptput in the console,But the value is not received after that .So how can i keep this socket running ? What am I missing?
Thank you All
try this
create a class client.java
public class client{
Socket socket;
int Port;
InetAddress serverIp;
public boolean connection;
public client(String ip, int port) {
// TODO Auto-generated constructor stub
try {
serverIp = InetAddress.getByName(ip);
Port = port;
connect();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
connection = false;
}
}
public void connect(){
try {
System.out.println("wait connection client "+serverIp+" "+Port);
socket = new Socket(serverIp, Port);
connection = true;
} catch (IOException e) {
//e.printStackTrace();
connection = false;
}
}
public boolean send(String message) throws IOException {
byte[] data=message.getBytes();
OutputStream out = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
int len = data.length;
dos.writeInt(len);
if (len > 0) {
dos.write(data, 0, len);
}
return true;
}
public String read() {
InputStream in = null;
try {
in = socket.getInputStream();
} catch (IOException e) {
connection=false;
e.printStackTrace();
}
DataInputStream dis = new DataInputStream(in);
try {
int len = dis.readInt();
byte[] data = new byte[len];
if (len > 0) {
dis.readFully(data);
}
String result = new String(data, 0, data.length);
return result;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
connection=false;
}
return "";
}
and create a object of client.java in your activity onCreate
client con=new client("10.20.50.68", 8888);
and use con.send("your_data") to sent and String data=con.read(); to receive data...
if you want asynchronous listening of data in socket, use thread

Multiple Clients in Client Server app in C#

using resources at http://www.developerfusion.com i came up with the following server code. It works well for single client. How can i make it for multiple clients. I tried adding array and different instances of the beiginreceive but was unable to. The server code:
class Program
{
public static AsyncCallback pfnWorkerCallBack;
public static Socket m_socListener;
public static Socket m_socWorker;
static void Main(string[] args)
{
try
{
//create the listening socket...
m_socListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, 8221);
//bind to local IP Address...
m_socListener.Bind(ipLocal);
Console.WriteLine("UCManager Started");
//start listening...
m_socListener.Listen(4);
// create the call back for any client connections...
m_socListener.BeginAccept(new AsyncCallback(OnClientConnect), null);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
public static void OnClientConnect(IAsyncResult asyn)
{
try
{
m_socWorker = m_socListener.EndAccept(asyn);
WaitForData(m_socWorker);
}
catch (Exception se)
{
Console.WriteLine(se.Message);
}
}
public class CSocketPacket
{
public System.Net.Sockets.Socket thisSocket;
public byte[] dataBuffer = new byte[1];
}
public static void WaitForData(System.Net.Sockets.Socket soc)
{
try
{
if (pfnWorkerCallBack == null)
{
pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
}
CSocketPacket theSocPkt = new CSocketPacket();
theSocPkt.thisSocket = soc;
// now start to listen for any data...
soc.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, pfnWorkerCallBack, theSocPkt);
}
catch (SocketException se)
{
Console.WriteLine(se.Message);
}
}
public static void OnDataReceived(IAsyncResult asyn)
{
try
{
CSocketPacket theSockId = (CSocketPacket)asyn.AsyncState;
//end receive...
int iRx = 0;
iRx = theSockId.thisSocket.EndReceive(asyn);
char[] chars = new char[iRx + 1];
Decoder d = Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0);
String szData = new String(chars);
Console.WriteLine(szData);
int code = Convert.ToInt32(szData);
WaitForData(m_socWorker);
}
catch (Exception se)
{
Console.WriteLine(se.Message);
}
}
}
}
EDIT: Ok i did something on the lines of Async TCP Server for multiple Clients.
public static void OnClientConnect(IAsyncResult asyn)
{
try
{
Socket m_socWorkerInstance = m_socListener.EndAccept(asyn);
clientSocketList.Add(m_socWorkerInstance);
WaitForData(m_socWorkerInstance);
}
catch (ObjectDisposedException)
{
System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");
}
catch (SocketException se)
{
Console.WriteLine(se.Message);
}
}
public static void WaitForData(System.Net.Sockets.Socket soc)
{
try
{
if (pfnWorkerCallBack == null)
{
pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
}
CSocketPacket theSocPkt = new CSocketPacket();
theSocPkt.thisSocket = soc;
// now start to listen for any data...
soc.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, pfnWorkerCallBack, theSocPkt);
m_socListener.BeginAccept(new AsyncCallback(OnClientConnect), null);
}
catch (SocketException se)
{
Console.WriteLine(se.Message);
}
}
Now i am able to connect two clients but not able to communicate ...I am unable to send message from server to client...any suggestions...also should i have different read functions for both clients if i connect with two client???
You call BeginAccept only once, so after one client has been accepted, your server won't accept any new connections. You should call BeginAccept again after accepting a connection.
Ok i was able to solve it using Async TCP Server for multiple Clients:
public static void OnClientConnect(IAsyncResult asyn)
{
try
{
Socket m_socWorkerInstance = m_socListener.EndAccept(asyn);
clientSocketList.Add(m_socWorkerInstance);
WaitForData(m_socWorkerInstance);
}
catch (ObjectDisposedException)
{
System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");
}
catch (SocketException se)
{
Console.WriteLine(se.Message);
}
}
public static void WaitForData(System.Net.Sockets.Socket soc)
{
try
{
if (pfnWorkerCallBack == null)
{
pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
}
CSocketPacket theSocPkt = new CSocketPacket();
theSocPkt.thisSocket = soc;
// now start to listen for any data...
soc.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, pfnWorkerCallBack, theSocPkt);
m_socListener.BeginAccept(new AsyncCallback(OnClientConnect), null);
}
catch (SocketException se)
{
Console.WriteLine(se.Message);
}
}

Categories

Resources