i have a problem
i am writing a code in C#
i wanna receive a byte from serial port
but when i wanna receive data from port that sounds my program is hang
and doesnt work any more
SerialPort port = new SerialPort("COM3");
port.Open();
byte[] b = new byte[10];
port.Read(b, 0, 1);
port.Close();
please help me
This is because SerialPort reads data synchronously and blocks current thread until the data would be available.
You can use separate thread for this:
public class SerialPort : IDisposable
{
public SerialPort(byte comNum, int baudRate)
{
this.comNum = comNum;
serialPort = new System.IO.Ports.SerialPort("COM" + comNum.ToString(), baudRate);
serialPort.Open();
thread = new System.Threading.Thread(ThreadFn);
thread.Start();
}
public void Dispose()
{
if (thread != null)
thread.Abort();
if (serialPort != null)
serialPort.Dispose();
}
private void OnReceiveByte(byte b)
{
//handle received byte
}
private void ThreadFn(object obj)
{
Byte[] inputBuffer = new Byte[inputBufferSize];
while (true)
{
try
{
int availibleBytes = serialPort.BytesToRead;
if (availibleBytes > 0)
{
int bytesToRead = availibleBytes < inputBufferSize ? availibleBytes : inputBufferSize;
int readedBytes = serialPort.Read(inputBuffer, 0, bytesToRead);
for (int i = 0; i < readedBytes; i++)
OnReceiveByte(inputBuffer[i]);
}
System.Threading.Thread.Sleep(1);
}
catch (System.Threading.ThreadAbortException)
{
break;
}
catch (Exception e)
{
System.Diagnostics.Debug.Assert(false, e.Message);
}
}
}
private Byte comNum;
private System.IO.Ports.SerialPort serialPort;
private System.Threading.Thread thread;
private const int inputBufferSize = 1024;
}
Is there actually any data being sent over the serial port? The call to Read might just be waiting to receive some data before returning. Make sure that you have set a value for the ReadTimeout property. This will make the call to Read throw a TimeoutException if no data was read from the port.
Reference:
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.readtimeout.aspx
Also make sure you set the serial speed right (if you're reading too fast you'll miss some data, etc)
Related
I want to display a string when I receive data from a server. For that I was thinking on using delegates and events. I'm new to this topic (Delegates and Events) so I'm have not been able to set this up.
Here is what I've done:
public delegate void ClientHandleData(byte[] data, int bytesRead);
public event ClientHandleData OnDataReceived;
public void ConnectToServer(string ipAddress, int port)
{
this.port = port;
tcpClient = new TcpClient(ipAddress, port);
clientStream = tcpClient.GetStream();
Thread t = new Thread(new ThreadStart(ListenForData));
started = true;
t.Start();
}
private void ListenForData()
{
int bytesRead;
while (started)
{
bytesRead = 0;
try
{
bytesRead = clientStream.Read(buffer.ReadBuffer, 0, readBufferSize);
}
catch
{
//A socket error has occurred
MessageBox.Show("A socket error has occurred);
break;
}
if (OnDataReceived != null)
{
// display string to a textbox on the UI
}
Thread.Sleep(15);
}
started = false;
Disconnect();
}
You can just write
OnDataReceived?.Invoke(buffer.ReadBuffer, bytesRead);
If you want to be sure that your event will not be set to null after the if statement you can do this:
var handler = OnDataReceived;
handler?.Invoke(buffer.ReadBuffer, bytesRead);
Be careful when updating UI, because you can only update UI from UI thread. If you are using WPF you can do this:
Dispatcher.Invoke(() => {
// Update your UI.
});
And also make sure that someone actually subscribed to the event:
public void Foo()
{
objectWithTheEvent.OnDataReceived += OnOnDataReceived;
}
private void OnOnDataReceived(byte[] data, int count)
{
}
Let us have a look at your TcpClient listening code. When you call stream.Read() you can not be sure how much data will be read from your socket so you have to read until the end of the stream or you have to know how much date you are supposed to read from socket. Let us assume that you know how much data you are supposed to read
var readSofar = 0;
var iNeedToRead = 500;//500Bytes
try{
while(readSoFar<iNeedToRead){
var readFromSocket = clientStream.Read(buffer.ReadBuffer, readSofar, readBufferSize-readSofar);
if(readFromSocket==0){
//Remote server ended your connection or timed out etc
//Do your error handling may be stop reading
}
readSofar += readFromSocket;
}
}
catch {
//A socket error has occurred
MessageBox.Show("A socket error has occurred);
break;
}
if (OnDataReceived != null){
// display string to a textbox on the UI
}
You can use null propogation operator like this.
OnDataReceived?.Invoke(buffer.ReadBuffer, bytesRead);
If you are using WindowsForm each controller has to be updated from UI thread therefore you have to call from the subscriber method
private void IReceivedData(byte[] data, int count){
this.Invoke(()=>{...Your code});
}
I need to wait for the user to input data to the serialport reader and then process the data. However, using this code blocks the UI which is not what I want. Any ideas on how to make sure that data is received or a timeout has occured before continuing?
The reason I use
do
{
Thread.Sleep(1);
} while (...)
is because without it the code return indata before the user has time to change it.
I call ReadFromSerial from the main function and process the data there. If anything goes wrong I want it to return an empty string.
public string ReadFromSerial()
{
try
{
System.IO.Ports.SerialPort Serial1 = new System.IO.Ports.SerialPort("COM1", 9600, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One);
var MessageBufferRequest = new byte[13] { ... };
int BufferLength = 13;
if (!Serial1.IsOpen)
{
Serial1.Open();
}
Serial1.Write(MessageBufferRequest, 0, BufferLength); //Activates the serialport reader
indata = "";
Stopwatch timer = new Stopwatch();
timer.Start();
Serial1.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
do
{
Thread.Sleep(1);
} while (string.IsNullOrEmpty(indata) && timer.Elapsed.TotalSeconds < 10);
timer.Stop();
if (Serial1.IsOpen)
{
Serial1.Close();
}
return indata;
}
catch (Exception ex)
{
return "";
}
}
private static string indata;
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
try
{
SerialPort sp = (SerialPort)sender;
if (sp.BytesToRead > 0)
{
indata = sp.ReadExisting();
}
}
catch(InvalidOperationException)
{
;
}
}
This is where multi-threading, tasks, async programming and/or event handlers comes in handy. All of them offer something to help you get around stuff like this, depending on the types of objects you're using.
A good starting point in this case would be to run the whole receive loop as a separate thread, then send the received data back to the main thread in some fashion.
Here's the source of a form that does basically what yours does, but either as a Thread or a Task:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// Button: starts Task version
private void button1_Click(object sender, EventArgs e)
{
StartReceiveTask();
}
// Button: starts Thread version
private void button2_Click(object sender, EventArgs e)
{
StartReceiveThread();
}
// Start the Receive loop as a Task
public void StartReceiveTask()
{
System.Threading.Tasks.Task.Run(() => receiveThreadFunc());
}
// Start the Receive loop as a Thread
public void StartReceiveThread()
{
var thd = new System.Threading.Thread(receiveThreadFunc);
thd.Start();
}
// Called when the Receive loop finishes
public void DataReceived(string data)
{
// do something with the data here
}
// The Receive loop, used by both Thread and Task forms.
public void receiveThreadFunc()
{
using (var serial1 = new System.IO.Ports.SerialPort("COM1", 9600, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One))
{
// open serial port
if (!serial1.IsOpen)
serial1.Open();
// send init command
var initCommand = new byte[13];
serial1.Write(initCommand, 0, initCommand.Length);
// get start time
DateTime start = DateTime.Now;
// buffer for pushing received string data into
StringBuilder indata = new StringBuilder();
// loop until at most 10 seconds have passed
while ((DateTime.Now - start).TotalSeconds < 2)
{
if (serial1.BytesToRead > 0)
{
// allocate a buffer, up to 1K in length, to receive into
int blen = Math.Min(1024, serial1.BytesToRead);
byte[] buffer = new byte[blen];
// read chunks of data until none left
while (serial1.BytesToRead > 0)
{
int rc = serial1.Read(buffer, 0, blen);
// convert data from ASCII format to string and append to input buffer
indata.Append(Encoding.ASCII.GetString(buffer, 0, rc));
}
}
else
System.Threading.Thread.Sleep(25);
// check for EOL
if (indata.Length > 0 && indata.ToString().EndsWith("\r\n"))
break;
}
if (indata.Length > 0)
{
// post data to main thread, via Invoke if necessary:
string data = indata.ToString();
if (this.InvokeRequired)
this.Invoke(new Action(() => { DataReceived(data); }));
else
this.DataReceived(data);
}
}
}
}
I went with solution not to touch what I had already written. Instead I added these methods in my main function.
private void StartReceiveThread()
{
var thd = new System.Threading.Thread(receiveThreadFunc);
thd.Start();
}
private void receiveThreadFunc()
{
string str = Read.ReadFromSerial();
DataReceived(str);
}
private void DataReceived(string data)
{
//Process the data received
}
I wrote a service to send sensor data over bluetooth on android. Although I got no errors my C# client stops getting data after I sent exactly 561K data. At this moment it seems like my android continues to send data but my client doesn't get any. After a while, android also stops sending data. I tried different configurations. My program always stops sending data after "Service->Server". I don't get any errors but it stops sending. Here is android program.
#Override
public synchronized int onStartCommand(Intent intent, int flags, int startId) {
Log.i(EXTRA_MESSAGE,"onStartCommand");
if(isRunning)
Log.e(EXTRA_MESSAGE, "I am already running");
else
{
isRunning = true;
BluetoothDevice selectedDevice = (BluetoothDevice) intent.getParcelableExtra(EXTRA_MESSAGE);
if(selectedDevice == null)
{Log.i(EXTRA_MESSAGE,"null it is "); return -1;}
connect = new ConnectThread(selectedDevice);
connect.start();
mHandler =new Handler(){
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch(msg.what){
case SUCCESS_CONNECT:
connected = new ConnectedThread((BluetoothSocket) msg.obj);
Toast.makeText(getApplicationContext(), "Connected", 0).show();
//connected.write(("Connected").getBytes());
Log.i(EXTRA_MESSAGE, "we are connected");
isConnected = true;
break;
case MESSAGE_READ:
Toast.makeText(getApplicationContext(), ((byte[]) msg.obj).toString(), 0).show();
break;
}
}
};
mSensor = (SensorManager) getSystemService(SENSOR_SERVICE);
sSensor = mSensor.getDefaultSensor(Sensor.TYPE_ORIENTATION);
mSensor.registerListener(this, sSensor,SensorManager.SENSOR_DELAY_NORMAL);
// sSensor = mSensor.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
// mSensor.registerListener(this, sSensor,SensorManager.SENSOR_DELAY_NORMAL);
sSensor = mSensor.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
mSensor.registerListener(this, sSensor,SensorManager.SENSOR_DELAY_NORMAL);
}
return super.onStartCommand(intent, flags, startId);
}
#Override
#Override
public void onSensorChanged(SensorEvent event) {
Log.i(EXTRA_MESSAGE, "Sensor data arrived");
if(isConnected )
{
String toSend = Integer.toString(event.sensor.getType())+ ":" + Long.toString(event.timestamp)+ ":";
for(float f : event.values){
toSend = toSend + Float.toString(f)+":";
}
//
connected.write(toSend.getBytes());
}
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
Log.i(EXTRA_MESSAGE,"connectThread started successfully");
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
Log.i(EXTRA_MESSAGE,"connectThread connect successfully");
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
Log.i(EXTRA_MESSAGE,"connectThread connect exception");
try {
mmSocket.close();
} catch (IOException closeException) { }
}
// Do work to manage the connection (in a separate thread)
mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public boolean shouldContinue = true;
int nBytes =0;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
Log.i(EXTRA_MESSAGE,"connectedThread sockets");
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while(shouldContinue) {
try {
// Read from the InputStream
buffer = new byte[1024];
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
Log.e(EXTRA_MESSAGE, " We read");
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
Log.i(EXTRA_MESSAGE,"Service->Server");
mmOutStream.write(bytes);
nBytes += bytes.length;
Log.i(EXTRA_MESSAGE,"ok" + String.valueOf(nBytes ));
} catch (IOException e) {
Log.i(EXTRA_MESSAGE,"exception");
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
shouldContinue = false;
mmSocket.close();
} catch (IOException e) { }
}
}
Also my c# thread is as follows
public void ServerConnectThread()
{
serverStarted = true;
int counter = 0;
updateUI("Server started, waiting for clients");
BluetoothListener blueListener = new BluetoothListener(mUUID);
blueListener.Start();
BluetoothClient conn = blueListener.AcceptBluetoothClient();
updateUI("Client has connected");
Stream mStream = conn.GetStream();
while (true)
{
try
{
//handle server connection
byte[] received = new byte[1024];
mStream.Read(received, 0, received.Length);
counter += Encoding.ASCII.GetString(received).Length;
String[] fields = Encoding.ASCII.GetString(received).Split(':');
double[] data = new double[3];
for (int i = 2; i < 5; i++) data[i-2] = double.Parse(fields[i]);
//mSource.notifyObserver(Int16.Parse(fields[0]), data);
updateUI(counter.ToString() + " "+ fields[2]+ ":" + fields[3] + ":" + fields[4]);
byte[] sent = Encoding.ASCII.GetBytes("Hello World");
mStream.Write(sent, 0, sent.Length);
}
catch (IOException exception)`enter code here`
{
updateUI("Client has disconnected!!!!");
}
}
}
One final thing is I've found thousands of 561K android program which sounded a little interesting.
Ok I found my own problem. Basically I m sending a reply from my client when I got the sensor data and It is not handled by android app.
I have an application which connects with an external protocol
using serial communication.
I need know if the wakeup bit is set on each packet it sends to me (the 9 bit), and as communication rates must be below 40ms, and response must be sent under 20 ms.
The framework, encapsulates the bits read from the port, and only send back the 8 bits of data to me. Also, I cannot wait for the parity error event, because of timing issues.
I need to know how can I read the 9 bit, or if there is a free alternative to http://www.wcscnet.com/CdrvLBro.htm
Did you try to put your serial read function right in the parity error event handler? Depending on the driver, this might be fast enough.
This wouldn't happen to be for a certain slot machine protocol, would it? I did this for fun for you. Maybe it will work?
{
public Form1()
{
InitializeComponent();
}
SerialPort sp;
private void Form1_Load(object sender, EventArgs e)
{
sp = new SerialPort("COM1", 19200, Parity.Space, 8, StopBits.One);
sp.ParityReplace = 0;
sp.ErrorReceived += new SerialErrorReceivedEventHandler(sp_SerialErrorReceivedEventHandler);
sp.ReadTimeout = 5;
sp.ReadBufferSize = 256;
sp.Open();
}
object msgsLock = new object();
Queue<byte[]> msgs = new Queue<byte[]>();
public void sp_SerialErrorReceivedEventHandler(Object sender, SerialErrorReceivedEventArgs e)
{
if (e.EventType == SerialError.RXParity)
{
byte[] buffer = new byte[256];
try
{
int cnt = sp.Read(buffer, 0, 256);
byte[] msg = new byte[cnt];
Array.Copy(buffer, msg, cnt);
if (cnt > 0)
{
lock (msgsLock)
{
msgs.Enqueue(msg);
}
}
}
catch
{
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (msgs.Count > 0)
{
lock (msgsLock)
{
listBox1.Items.Insert(0, BitConverter.ToString(msgs.Dequeue()));
}
}
}
}
}
Anyways, for more control over the serial port I suggest using the win32 calls to get what you want.
http://msdn.microsoft.com/en-us/magazine/cc301786.aspx
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.