C# server and Android Client - c#

I'm working on two programs, one software Microsoft visual studio 2010 when I run a server and a second program : Eclipse ADT (ANDROID device development environment) in which I supposedly client. The goal is to establish a connection between SERVER in C# and Android CLIENT. It should not be a problem, I tried on TCP and UDP tried on, it falls on both object creation context (in TCP that falls on the object socket and UDP SOCKET falls DATAGRAM object creation), it seems to me the problem is: activitythread.performlaunchactivity (activitythread $ activityclientreco rd intent) line 2247
As I understand the problem is not in my code snippet but the SOCKET supplementation with software built into Eclipse, I tried to re-install, add the latest plugin. To your next question, I did permissions for Android device and internet. This I have no idea how to approach this problem which I am going for a month or more ..
In addition I'll add my code in android client :
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.util.Log;
public class MainActivity extends Activity {
private TextView txt;
private Button b;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button)findViewById(R.id.button1);
txt = (TextView)findViewById(R.id.textView1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
connectSocket("Hello");
}
});
}
private void connectSocket(String a){
try {
InetAddress serverAddr = InetAddress.getByName("10.0.0.8");
Log.d("TCP", "C: Connecting...");
**Socket socket = new Socket(serverAddr, 4444);**
String message = "1";
PrintWriter out = null;
BufferedReader in = null;
try {
Log.d("TCP", "C: Sending: '" + message + "'");
out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println(message);
while ((in.readLine()) != null) {
txt.append(in.readLine());
}
Log.d("TCP", "C: Sent.");
Log.d("TCP", "C: Done.");
} catch(Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
socket.close();
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.e("TCP", "C: UnknownHostException", e);
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("TCP", "C: IOException", e);
e.printStackTrace();
}
}
}
and my server in C# :
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
public class TestTCP
{
public static void Main()
{
try
{
IPAddress ipAd = IPAddress.Parse("127.0.0.1");
// use local m/c IP address, and
// use the same in the client
/* Initializes the Listener */
TcpListener myList = new TcpListener(ipAd, 11000);
/* Start Listeneting at the specified port */
myList.Start();
Console.WriteLine("The server is running at port 11000...");
Console.WriteLine("The local End point is :" +
myList.LocalEndpoint);
Console.WriteLine("Waiting for a connection.....");
m:
Socket s = myList.AcceptSocket();
Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
byte[] b = new byte[100];
int k = s.Receive(b);
char cc = ' ';
string test = null;
Console.WriteLine("Recieved...");
for (int i = 0; i < k - 1; i++)
{
Console.Write(Convert.ToChar(b[i]));
cc = Convert.ToChar(b[i]);
test += cc.ToString();
}
switch (test)
{
case "1":
break;
}
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes("The string was recieved by the server."));
Console.WriteLine("\nSent Acknowledgement");
/* clean up */
goto m;
s.Close();
myList.Stop();
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
}
}
Thanks.

First of all you may not run the connecSocket method in your UI thread. You have to do something like this:
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Thread stackOverflow = new Thread(new Runnable() {
#Override
public void run() {
connectSocket("Hello");
}});
stackOverflow.start();
}
});
Otherwise you get this exception:
android.os.NetworkOnMainThreadException
Secondly you must connect to the same port and interface where your server is listening:
IPAddress ipAd = IPAddress.Parse("127.0.0.1");
Should be the same address as the one you are using in your Android application:
IPAddress ipAd = IPAddress.Parse("10.0.0.8");
And your Android application must connect to the same port where server is listening:
Socket socket = new Socket(serverAddr, 11000);
Finally do not forget the Android permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
And be careful with firewalls and things like that, they could also drop your connections.

Related

send data from socket to c# in android

I am trying to develop an application in android to sent the gps data to my pc .the android part is :
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
float latitude = (float) (location.getLatitude());
float longitude = (float) (location.getLongitude());
showMessage("Student Details", "Latitude: " + latitude + ", Longitude: " + longitude);
Log.i("Geo_Location", "Latitude: " + latitude + ", Longitude: " + longitude);
try {
Socket socket = new Socket("192.168.1.5",5000);
DataOutputStream DOS = new DataOutputStream(socket.getOutputStream());
DOS.writeUTF("HELLO_WORLD");
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And the c# code or server code is :
public AsyncCallback pfnWorkerCallBack;
private Socket m_mainSocket;
private Socket[] m_workerSocket = new Socket[25];
private int m_clientCount = 0;
private string ipaddress;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
startfun();
}
public void startfun()
{
try
{
// DrawMapPersian();
ipaddress = "192.168.1.5";
// Check the port value
string portStr = "5000";
int port = System.Convert.ToInt32(portStr);
// Create the listening socket...
m_mainSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, port);
// Bind to local IP Address...
m_mainSocket.Bind(ipLocal);
listBox1.Items.Add("Server Started...");
// Start listening...
m_mainSocket.Listen(20);
listBox1.Items.Add("Server Listening for ...");
// Create the call back for any client connections...
m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
}
catch (Exception qqq)
{
using (StreamWriter writer =
new StreamWriter(#"e:\a.txt"))
{
writer.Write(qqq.Message);
}
}
}
public void OnDataReceived(IAsyncResult asyn)
{
try
{
SocketPacket socketData = (SocketPacket)asyn.AsyncState;
int iRx = 0;
// Complete the BeginReceive() asynchronous call by EndReceive() method
// which will return the number of characters written to the stream
// by the client
iRx = socketData.m_currentSocket.EndReceive(asyn);
string res = GetParameters(socketData.dataBuffer);
Console.WriteLine(res.ToString());
}
another thing that i should say i add this permissions to manifest <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.INTERNET" />
I connected the mobile phone to the wireless network ,i mean the mobile can access my ip .
The problem is the gps data is generated so slowly i don't know why ?another problem is the android application doesn't send any data to server ,
Client
To accelerate the location update, you have to specify to the Activity the location update interval when setting the LocationListener implementation.
Something like :
LocationListener impl = new MyLocationListenerImpl();
long interval = 4000;//change your code here
setLocationListener(impl, interval);
(Note that the code above is more like a pseudo code, since It's been a long time since I have touched LocationListener).
Server
The code you provided does not mention the "OnDataReceived" member function. So I think that you should dig in this way.
Unless sockets are used on purpose, consider using Http Protocol and frameworks like ASP.NET and loopj Async Http to pass data to a server, it's easier !

android bufferReader.readLine() returns rubbish data from C# TCP client occasionally?

i have build a chat application that uses UDP and TCP sockets, first let me walk you through the mechanism of the app:
from the android device i send a UDP packet to a group address which has multiple windows devices listening to it, when the windows device receives the packet, it checks whether it has the same phone number or not so i use the phone number as a unique key to identify the device then if it has the same phone number that I've send the packet with, it will respond with a key says: "ImReadyNow" sent through a TCP socket and that will make the android device accept the connection and act as a server for that windows device, i had similar problems when i first start making that app, the respond key from the windows device was returned with some rubbish data before and after it and i solved that problem by attaching a key to that massage and i split it after releasing so that old problem that i was facing was when a windows device sends "Hello" the android device receives
"????Hello" i solved this one by attaching a key to the first of the massage so
i'll receives "????$#!Hello" then i'll split the received string into two parts and displays the massage only, and that works fine for me till, i notice that sometimes the android device receives rubbish data only and that occurs randomly like if windows device sends "hello" then "hi" then "hello"
i may receives the first two massages right but the third one will received as "?????"
and as i told you it occurs randomly so does any one know why is this happening?
after debugging br.readLine() method does sometimes return "????" and this occurs as i said randomly.
here is the code that i'm using:
private class ChatClientThread extends Thread {
#Override
public void run() {
/*Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream=null;*/
// clientSocket=null;
try {
String data=EmpPhoneNumber;
DatagramChannel channel = DatagramChannel.open();
DatagramSocket socket = channel.socket();
socket.setReuseAddress(true);
socket.bind(new InetSocketAddress(52276));
socket.setBroadcast(true);
InetAddress group = InetAddress.getByName(
"224.0.1.2");
System.out.println("HELLO");
System.out.println(data);
DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length(),
group, 52276);
serverSocket=new ServerSocket();
serverSocket.setReuseAddress(true);
serverSocket.bind(new InetSocketAddress(4125));
int i=0;
while(i<=30){
Thread.sleep(200);
socket.send(packet);
i++;
}
while(true){
clientSocket = serverSocket.accept();
BufferedReader br= new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
strAcceptConnection= br.readLine();
System.out.println(strAcceptConnection);
if(!strAcceptConnection.contains("$#!")){
updateTextView("<font color=\"#0000A0\"> <b>"+empNameChat+": </b></font>"+"Error in recieving msg");
}else{
String parts[]= strAcceptConnection.split("[$#!]+");
if(!parts[1].equals("ImReadyNoW")){
updateTextView("<font color=\"#0000A0\"> <b>"+empNameChat+": </b></font>"+parts[2]);
}}}
} catch (UnknownHostException e) {
e.printStackTrace();
final String eString = e.toString();
EmpDetails.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(EmpDetails.this, eString, Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
e.printStackTrace();
final String eString = e.toString();
EmpDetails.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(EmpDetails.this, eString, Toast.LENGTH_LONG).show();
}
});
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
} finally {
EmpDetails.this.runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
}
}
public void sendMessage(View view) {
final String msg= et.getText().toString();
et.setText("");
new Thread(new Runnable() {
public void run() {
Socket sock= null;
try {
sock= new Socket(clientSocket.getInetAddress().getHostAddress(), 4125);
Log.v("str", "send sock: "+sock.getInetAddress().getHostAddress()+sock.isConnected()+Integer.toString(sock.getPort()));
} catch (UnknownHostException e) {
Log.v("ERRORTAG", ""+e.getMessage());
e.printStackTrace();
} catch (IOException e) {
Log.v("ERRORTAG", ""+e.getMessage());
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
try {
DataOutputStream out= new DataOutputStream(sock.getOutputStream());
if(!msg.equals("")){
out.writeUTF("XX$#!"+MainActivity.empIdFromD+"$#!"+msg);
out.flush();
updateTextView("<font color=\"#800000\"> <b>"+"You"+": </b></font>" + msg);}
}
catch (IOException e) {
Log.v("ERRORTAG", ""+e.getMessage());
e.printStackTrace();
}
}
}).start();
}
public void updateTextView(String message) {
final String msg= message;
uiHandle.post(new Runnable() {
public void run() {
textView.setMovementMethod(new ScrollingMovementMethod());
Log.v("TAG", "updating textview");
//textView.append(msg+"\n");
textView.append(Html.fromHtml(msg));
textView.append("\n");
Log.v("TAG", "updated textview");
ScrollView sc= (ScrollView)findViewById(R.id.scrollView1);
sc.fullScroll(View.FOCUS_DOWN);
}
});
}
how does the received string look like:
LogCat:
PS. on the other side the windows device receives all of the massages correctly.

C# Client and Android Listener

i am new to this website but have been reading alot since long.
I am little confused with this IP stuff, i am reasonable programmer but very poor at IP thing.
I want to implement C# client with Android Server[Android device moves around the world so first thing is to get its IP address].
I have written[copied] following android code from stackOverflow question and trying to use it.
public static String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
String ip = Formatter.formatIpAddress(inetAddress.hashCode());
Log.i("IP", "***** IP="+ ip);
return ip;
}
}
}
} catch (SocketException ex) {
Log.e("EXCPTN", ex.toString());
}
return null;
}
Question 1: It gives me some Ip lets say 142.171.13.206 , but when i check my Ip by googling 'what is my ip' from my andoird decide, i totally get new IP [120.100.78.14]. What wrong i am doing? I am running on Wifi, no edge no 3g or something.
Question 2: If i have a C# client, which android IP should i try to connect ? Becuase i am unable to connect to android server.
My C# Client code is something like this
try
{
const int Port = 4321;
TcpClient ourMagicClient = new TcpClient();
//Connect to the server - change this IP address to match your server's IP!
ourMagicClient.Connect("192.177.111.200", Port);
//Use a NetworkStream object to send and/or receive some data
NetworkStream ourStream = ourMagicClient.GetStream();
//Let's set up some data!
byte[] data = Encoding.ASCII.GetBytes("Plz recieve this msg!");
//Everyone ready? Send that bad-boy!
ourStream.Write(data, 0, data.Length); //Start at the 0'th position in our string and send until the end of the string, but we can stop there...
}
catch (Exception ex)
{
textBox1.Text = ex.ToString();
}
And finally here is the code for my android listener running 4.4 Kitkat
private class SocketServerThread extends Thread {
static final int SocketServerPORT = 4321;
int count = 0;
#Override
public void run() {
try {
serverSocket = new ServerSocket(SocketServerPORT);
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
info.setText("I'm waiting here: "
+ serverSocket.getLocalPort());
;
}
});
while (true) {
Socket socket = serverSocket.accept();
count++;
message += "#" + count + " from " + socket.getInetAddress()
+ ":" + socket.getPort() + "\n";
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(message);
}
});
SocketServerReplyThread socketServerReplyThread = new SocketServerReplyThread(
socket, count);
socketServerReplyThread.run();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class SocketServerReplyThread extends Thread {
private Socket hostThreadSocket;
int cnt;
SocketServerReplyThread(Socket socket, int c) {
hostThreadSocket = socket;
cnt = c;
}
#Override
public void run() {
OutputStream outputStream;
String msgReply = "Hello from Android, you are #" + cnt;
try {
outputStream = hostThreadSocket.getOutputStream();
PrintStream printStream = new PrintStream(outputStream);
printStream.print(msgReply);
printStream.close();
message += "replayed: " + msgReply + "\n";
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(message);
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
message += "Something wrong! " + e.toString() + "\n";
}
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(message);
}
});
}
}
I have googles alot, searched this website too, but i am unable to connect C# client with Andoird server. Plz help me with the code what n where to fix. Or if you have totally different working code plz share that with me.
Note: Thx to all those from which i have copied above code [unfortunately i dont have referece to thier websites]. Thx!

Server Side Socket c# network error

I am very new to programming c# in visual studio. I am trying to send a message from an android app (Client side) to a windows app (Server side) using sockets. I don't know if I should be able to do it in the wireless network that I have, or is that even the problem. Also can I pick and use any port number or it has to be a specific number that I have to fetch from somewhere? I will post both my client and server codes, and the output of my server side code. Any help is much appreciated.
Client:
public class MainActivity extends Activity {
private EditText editTxt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button)findViewById(R.id.button1);
editTxt = (EditText) findViewById(R.id.editText1);
final String str = editTxt.getText().toString();
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
connectSocket(str);
}
});
}
private void connectSocket(String a){
new Thread( new Runnable() {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName("10.5.5.117");
Log.d("TCP", "C: Connecting...");
Socket socket = new Socket(serverAddr, 5555);
String message = "1";
PrintWriter out = null;
BufferedReader in = null;
try {
Log.d("TCP", "C: Sending: '" + message + "'");
out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println(message);
String text = "";
String finalText = "";
while ((text = in.readLine()) != null) {
finalText += text;
}
editTxt.setText(finalText);
Log.d("TCP", "C: Sent.");
Log.d("TCP", "C: Done.");
} catch(Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
socket.close();
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.e("TCP", "C: UnknownHostException", e);
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("TCP", "C: IOException", e);
e.printStackTrace();
}
}}).start();
}
}
Server:
namespace WindowsSocketServer
{
public class serv
{
public static void Main()
{
try
{
IPAddress ipAd = IPAddress.Parse("10.5.5.117");
// use local m/c IP address, and
// use the same in the client
// Initializes the Listener
TcpListener myList = new TcpListener(ipAd, 5555);
// Start Listeneting at the specified port
myList.Start();
Console.WriteLine("The server is running at port 5555...");
Console.WriteLine("The local End point is :" +
myList.LocalEndpoint);
Console.WriteLine("Waiting for a connection.....");
m:
Socket s = myList.AcceptSocket();
Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
byte[] b = new byte[100];
int k = s.Receive(b);
char cc = ' ';
string test = null;
Console.WriteLine("Recieved...");
for (int i = 0; i < k - 1; i++)
{
Console.Write(Convert.ToChar(b[i]));
cc = Convert.ToChar(b[i]);
test += cc.ToString();
}
switch (test)
{
case "1":
break;
}
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes("The string was recieved by the server."));
Console.WriteLine("\nSent Acknowledgement");
s.Close();
// clean up
goto m;
s.Close();
myList.Stop();
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
}
}
}
Server Output:
The thread 'vshost.NotifyLoad' (0x21e8) has exited with code 0 (0x0).
The thread '<No Name>' (0x1d04) has exited with code 0 (0x0).
The thread 'vshost.LoadReference' (0x2448) has exited with code 0 (0x0).
'WindowsSocketServer.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:\Projects\Offline\WindowsSocketServer\bin\Debug\WindowsSocketServer.exe', Symbols loaded.
'WindowsSocketServer.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50 a3a\System.Configuration.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Error..... at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.Sockets.Socket.Bind(EndPoint localEP)
at System.Net.Sockets.TcpListener.Start(Int32 backlog)
at System.Net.Sockets.TcpListener.Start()
at WindowsSocketServer.serv.Main() in
C:\Projects\Offline\WindowsSocketServer\Program.cs:line 27
A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.dll
The thread 'vshost.RunParkingWindow' (0x1a5c) has exited with code 0 (0x0).
The thread '<No Name>' (0x1ba4) has exited with code 0 (0x0).
The program '[8828] WindowsSocketServer.vshost.exe: Managed (v4.0.30319)' has exited with code 0 (0x0).
You should be able to get more information from the SocketException as to what the problem is. (Description, error code etc). I'm guessing that it breaking on Bind can simply be explained by port 5555 being already in use by another application (adb perhaps?). Usually only one application can listen on a given port, so try a different one. You can pick any port (< 1024 are reserved ports, but any above that up to 65535 are valid). Just update the client to connect to the new port too.

Sockets: Send strings from Java to C#?

I need to send string messages from Java program to C# program in real time.
There are many examples in the Internet but U can't find anything good for my purpose that is (probably) Java client (sockets code) and c# server (sockets code).
Thank you.
Ok i already did this in one of my projects so here it is:
disclaimer: some of the code (only a little bit actually) is based on nakov chat server.
also note that i decode and encode all the messages sent and recived in UTF-8.
Java Code:
Class: Server
import java.net.*;
import java.io.*;
import javax.swing.*;
public class Server
{
private static void createAndShowGUI() {
//Create and set up the window
}
public static final int LISTENING_PORT = 2002;
public static void main(String[] args)
{
// Open server socket for listening
ServerSocket serverSocket = null;
try
{
serverSocket = new ServerSocket(LISTENING_PORT);
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
//System.out.println("Server started on port " + LISTENING_PORT);
}
catch (IOException se)
{
System.err.println("Can not start listening on port " + LISTENING_PORT);
se.printStackTrace();
System.exit(-1);
}
// Start ServerDispatcher thread
ServerDispatcher serverDispatcher = new ServerDispatcher();
// Accept and handle client connections
while (true)
{
try
{
Socket socket = serverSocket.accept();
ClientInfo clientInfo = new ClientInfo();
clientInfo.mSocket = socket;
ClientListener clientListener =
new ClientListener(clientInfo, serverDispatcher);
ClientSender clientSender =
new ClientSender(clientInfo, serverDispatcher);
clientInfo.mClientListener = clientListener;
clientInfo.mClientSender = clientSender;
clientListener.start();
clientSender.start();
serverDispatcher.addClient(clientInfo);
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
}
Class Message Dispatcher:
import java.io.UnsupportedEncodingException;
import java.net.*;
import java.util.*;
public class ServerDispatcher
{
private Vector mMessageQueue = new Vector();
private Vector<ClientInfo> mClients = new Vector<ClientInfo>();
public synchronized void addClient(ClientInfo aClientInfo) {
mClients.add(aClientInfo);
}
public synchronized void deleteClient(ClientInfo aClientInfo) {
int clientIndex = mClients.indexOf(aClientInfo);
if (clientIndex != -1)
mClients.removeElementAt(clientIndex);
}
private synchronized void sendMessageToAllClients(String aMessage)
{
for (int i = 0; i < mClients.size(); i++) {
ClientInfo infy = (ClientInfo) mClients.get(i);
infy.mClientSender.sendMessage(aMessage);
}
}
public void sendMessage(ClientInfo aClientInfo, String aMessage) {
aClientInfo.mClientSender.sendMessage(aMessage);
}
}
Class: ClientInfo
/**
*
* ClientInfo class contains information about a client, connected to the server.
*/
import java.awt.List;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Vector;
public class ClientInfo
{
public int userID=-1;
public Socket mSocket = null;
public ClientListener mClientListener = null;
public ClientSender mClientSender = null;
}
Class ClientListner:
/**
* ClientListener class is purposed to listen for client messages and
* to forward them to ServerDispatcher.
*/
import java.io.*;
import java.net.*;
public class ClientListener extends Thread {
private ServerDispatcher mServerDispatcher;
private ClientInfo mClientInfo;
private BufferedReader mIn;
private String message;
private String decoded = null;
public ClientListener(ClientInfo aClientInfo,
ServerDispatcher aServerDispatcher) throws IOException {
mClientInfo = aClientInfo;
mServerDispatcher = aServerDispatcher;
Socket socket = aClientInfo.mSocket;
mIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
/**
* Until interrupted, reads messages from the client socket, forwards them
* to the server dispatcher and notifies the server dispatcher.
*/
public void run() {
message = "";
while (!isInterrupted()) {
try {
message = mIn.readLine();
if (message == null)
break;
try {
decoded = URLDecoder.decode(message, "UTF-8");
} catch (UnsupportedEncodingException e)
e.printStackTrace();
}
mServerDispatcher.sendMessage(mClientInfo, decoded);
}
catch (IOException e) {
break;
}
}
// Communication is broken. Interrupt both listener and sender threads
mClientInfo.mClientSender.interrupt();
mServerDispatcher.deleteClient(mClientInfo);
}
}
Class:ClientSender
/**
* Sends messages to the client. Messages are stored in a message queue. When
* the queue is empty, ClientSender falls in sleep until a new message is
* arrived in the queue. When the queue is not empty, ClientSender sends the
* messages from the queue to the client socket.
*/
import java.io.*;
import java.net.*;
import java.util.*;
public class ClientSender extends Thread
{
private Vector mMessageQueue = new Vector();
private ServerDispatcher mServerDispatcher;
private ClientInfo mClientInfo;
private PrintWriter mOut;
public ClientSender(ClientInfo aClientInfo, ServerDispatcher aServerDispatcher)
throws IOException
{
mClientInfo = aClientInfo;
mServerDispatcher = aServerDispatcher;
Socket socket = aClientInfo.mSocket;
mOut = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
}
/**
* Adds given message to the message queue and notifies this thread
* (actually getNextMessageFromQueue method) that a message is arrived.
* sendMessage is called by other threads (ServeDispatcher).
*/
public synchronized void sendMessage(String aMessage)
{
mMessageQueue.add(aMessage);
notify();
}
/**
* #return and deletes the next message from the message queue. If the queue
* is empty, falls in sleep until notified for message arrival by sendMessage
* method.
*/
private synchronized String getNextMessageFromQueue() throws InterruptedException
{
while (mMessageQueue.size()==0)
wait();
String message = (String) mMessageQueue.get(0);
mMessageQueue.removeElementAt(0);
return message;
}
/**
* Sends given message to the client's socket.
*/
private void sendMessageToClient(String aMessage)
{
String encoded;
try {
encoded = URLEncoder.encode(aMessage,"UTF-8");
mOut.println(encoded);
mOut.flush();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
/**
* Until interrupted, reads messages from the message queue
* and sends them to the client's socket.
*/
public void run()
{
try {
while (!isInterrupted()) {
String message = getNextMessageFromQueue();
sendMessageToClient(message);
}
} catch (Exception e) {
// Commuication problem
break;
}
// Communication is broken. Interrupt both listener and sender threads
mClientInfo.mClientListener.interrupt();
mServerDispatcher.deleteClient(mClientInfo);
}
}
Ok this is the java code,now to the c# code
c# Code:
Varibales used:
private StreamWriter swSender;
private StreamReader srReceiver;
private TcpClient tcpServer;
private Thread thrMessaging;
private IPAddress ipAddr;
private bool Connected;
Function: Intelize connection:
private void InitializeConnection()
{
// Parse the IP address
string ipAdress = "XXX.XXX.XXX.XXX";
ipAddr = IPAddress.Parse(ipAdress);
// Start a new TCP connections to the chat server
tcpServer = new TcpClient();
try
{
tcpServer.Connect(ipAddr, 2002);
swSender = new StreamWriter(tcpServer.GetStream());
// Start the thread for receiving messages and further communication
thrMessaging = new Thread(new ThreadStart(ReceiveMessages));
thrMessaging.Start();
Connected=true;
}
catch (Exception e2)
{
MessageBox.Show(e2.ToString());
}
}
}
Function: ReciveMessages
private void ReceiveMessages()
{
// Receive the response from the server
srReceiver = new StreamReader(tcpServer.GetStream());
while (Connected)
{
String con = srReceiver.ReadLine();
string StringMessage = HttpUtility.UrlDecode(con, System.Text.Encoding.UTF8);
processMessage(StringMessage);
}
}
Function: proceesMessage:
private void processMessage(String p)
{
// do something with the message
}
Function sendMessage:
private void SendMessage(String p)
{
if (p != "")
{
p = HttpUtility.UrlEncode(p, System.Text.Encoding.UTF8);
swSender.WriteLine(p);
swSender.Flush();
}
}
thats it thats all you need to have communication between java server and c# client. if you have any questions dont hesitate to post them here.
Choose a protocol for encoding/sending your strings. For instance:
<length of string (4 bytes)><string data (length bytes)>
Write some Java code to send a string that follows whatever protocol you chose in #1. So using the example above, you could do something like:
public static void writeString(String string, OutputStream out) throws IOEXception {
if (string == null || "".equals(string)) {
//nothing to do
return;
}
int length = string.length();
//synchronize so that two threads don't try to write to the same stream at the same time
synchronized(out) {
out.write((length >> 24) & 0xFF);
out.write((length >> 16) & 0xFF);
out.write((length >> 8) & 0xFF);
out.write(length & 0xFF);
out.write(string.getBytes());
out.flush();
}
}
Write some equivalent code in C# to decode the strings that are being sent. It will look a lot like your Java code, except with reads instead of writes.
I think I've found a good, working solution. Using UDP sockets:
Java code
public void runJavaSocket() {
System.out.println("Java Sockets Program has started."); int i=0;
try {
DatagramSocket socket = new DatagramSocket();
System.out.println("Sending the udp socket...");
// Send the Message "HI"
socket.send(toDatagram("HI",InetAddress.getByName("127.0.0.1"),3800));
while (true) {
System.out.println("Sending hi " + i);
Thread.currentThread();
Thread.sleep(1000);
socket.send(toDatagram("HI " +
String.valueOf(i),InetAddress.getByName("127.0.0.1"),3800));
i++;
}
} catch (Exception e) {
e.printStackTrace();
}
}
public DatagramPacket toDatagram(
String s, InetAddress destIA, int destPort) {
// Deprecated in Java 1.1, but it works:
byte[] buf = new byte[s.length() + 1];
s.getBytes(0, s.length(), buf, 0);
// The correct Java 1.1 approach, but it's
// Broken (it truncates the String):
// byte[] buf = s.getBytes();
return new DatagramPacket(buf, buf.length, destIA, destPort);
}
C# code
string returnData;
byte[] receiveBytes;
//ConsoleKeyInfo cki = new ConsoleKeyInfo();
using (UdpClient udpClient =
new UdpClient(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3800)))
{
IPEndPoint remoteIpEndPoint =
new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3800);
while (true)
{
receiveBytes = udpClient.Receive(ref remoteIpEndPoint);
returnData = Encoding.ASCII.GetString(receiveBytes);
Console.WriteLine(returnData);
}
}
I would just use SOAP protocol. You can use WCF on the C# side and JMS (Java messging) on the Java side. Both these technologies are built on SOAP so they can read each other's messages. They both use WSDL.

Categories

Resources