I have programmed a server and a client application under Xamarin C# (for PC and Android phone).
Now I have a problem with the umlauts (äöüÄÖÜ) at Text.Encoding.Default.GetBytes () / Encoding.Default.GetString ().
If the server and client running on the PC, umlauts are converted correctly. When operated smartphone and PC only question marks will be issued on conversion of umlauts. All other data is converted properly.
Where is the problem?
private void cButtonSend_Click(object sender, EventArgs e)
{
try
{
if (cAktiveClient == "") Toast.MakeText(this, "Wählen Sie einen Client aus!", ToastLength.Long).Show();
else
{
string txt = cSendeText.Text;
byte[] telegramm = new byte[txt.Length];
telegramm = System.Text.Encoding.Default.GetBytes(txt);
foreach (TcpClient c in cServer.ClientList)
{
if (c.Client.RemoteEndPoint.ToString() == cAktiveClient) cServer.Send(c, telegramm);
}
cSendeText.Text = "";
}
}
catch (Exception ex)
{
Toast.MakeText(this, ex.Message, ToastLength.Short).Show();
}
}
private void cServer_Recieve(object sender, EventArgs e)
{
// bei Aufrufen aus anderenThreads
this.RunOnUiThread(() =>
{
try
{
TCPIP_MultiServer t = sender as TCPIP_MultiServer;
cEmpfangsClient.Text = t.NowClient.Client.RemoteEndPoint.ToString();
cEmpfangsText.Text = Encoding.Default.GetString(cServer.Buffer, 0, cServer.RecievedBytes);
}
catch (Exception ex)
{
Toast.MakeText(this, ex.Message, ToastLength.Long).Show();
}
});
}
To reduce the size of the application, Xamarin doesn't include any specific encodings.
Read this:
https://developer.xamarin.com/guides/ios/advanced_topics/localization_and_internationalization/encodings/ (on Android it's the same)
And this:
https://developer.xamarin.com/guides/cross-platform/xamarin-forms/localization/
Related
I am using MQTT.fx and
"test.mosquitto.org"
locally as a broker. Now i want to send a message from the broker to Visual Studio (where I am connected with the client/broker). How does that work? What I have since now is:
Edit: Obviously
//await client.PublishAsync(new MqttApplicationMessage(topic,
Encoding.UTF8.GetBytes($"{message}")),
MqttQualityOfService.ExactlyOnce); //QOS 2
is not working at the moment...
private async void OnButton2Clicked(object sender, EventArgs e)
{
try
{
testLabel2.Text = "test";
await client.SubscribeAsync(topic, MqttQualityOfService.ExactlyOnce); //QOS 2
//await client.PublishAsync(new MqttApplicationMessage(topic, Encoding.UTF8.GetBytes($"{message}")), MqttQualityOfService.ExactlyOnce); //QOS 2
OnMessageReceived();
}
catch (Exception ex)
{
testLabel2.Text = "Ausnahme gefunden: " + ex.Message;
}
}
///////////////////////////////////////////////
private void OnMessageReceived()
{
MessagingCenter.Subscribe<IMqttClient>(topic, "Hallooo", (sender) =>
{
testLabel2.Text = "Du hast eine Nachricht bekommen";
});
}
private async void SubscriptionTemp() **// Here I make a method, to subscribe a temperature.**
{
if (MainPage.client2.IsConnected) **//Check if IMqttClient is connected**
{
await MainPage.client2.SubscribeAsync(topicTemp, MqttQualityOfService.AtMostOnce); // QOS 0
MainPage.client2
.MessageStream
.Where(msg => msg.Topic == topicTemp)
.Subscribe(msg => onTempRelayReceived(msg));
}
}
private void onTempRelayReceived(MqttApplicationMessage msg)
{
string msgEncoded = (Encoding.UTF8.GetString(msg.Payload)); // **Here I assign the payload received from mqtt as a string.**
tempRelay = double.Parse(msgEncoded);
}
Iam developing a WPF application to interact with ELM327. The communication medium between myApp and ELM327 is USB protocol. ELM327 is connected to vehicle through OBD port. My app able to establish USB communication successfully. Whatever command Iam sending from my App, Iam getting ? as reply. I set baud rate as 9600. For example, I sent ATZ, iam getting ? as reply. I sent 010D, I got ?. I tried with the app comes along with ELM327, that app can successfully able to extract data.
MyApp USB communication connect code:
public SerialPort sport;
private void Button_Click(object sender, RoutedEventArgs e)
{
int baudValue=0;
if (cbBaud.Text == null)
MessageBox.Show("select a baud rate");
else
{
if (cbBaud.Text != null)
{
baudValue = int.Parse(cbBaud.Text);
}
serialConnect(baudValue);
}
}
public void serialConnect(int baudRate)
{
try
{
if (tbCOM.Text != null)
{
sport = new System.IO.Ports.SerialPort(tbCOM.Text,
baudRate);
if (!sport.IsOpen)
{
sport.Open();
sport.DataReceived += new SerialDataReceivedEventHandler(serialDataReceived);
elIndicator.Fill = Brushes.Green;
}
else
{
MessageBox.Show("Connection already Opened");
}
}
}
catch(Exception EX)
{
MessageBox.Show("Connection Error");
}
}
MyApp data sent code:
private void BtSent_Click(object sender, RoutedEventArgs e)
{
try
{
sport.WriteLine(tbSend.Text);
}
catch(Exception EX)
{
MessageBox.Show("Write Error");
}
}
MyApp data receive code:
private void serialDataReceived(object sender, SerialDataReceivedEventArgs e)
{
this.Dispatcher.Invoke((Action)(() =>
{
recData.Text = "\n";
recData.Text = System.Environment.NewLine + sport.ReadExisting();
}));
}
Is there any initialization code amI have to sent ?
I am building an application , in which I need to have a c# server and nodejs client. I have built the components , but I am always getting ECONNREFUSED error. any leads when I can except this error?
FYI,
I am able to connect to c# server from c# client. similarly. I am able to connect to nodejs tcp server from nodejs tcp client. however the I am facing error with this mixture.
hey sorry for not adding code earlier.
the following is the c# server code:
using System;
using System.Text;
using AsyncClientServerLib.Server;
using System.Net;
using AsyncClientServerLib.Message;
using SocketServerLib.SocketHandler;
using SocketServerLib.Server;
namespace TestApp
{
delegate void SetTextCallback(string text);
public partial class FormServer : Form
{
private BasicSocketServer server = null;
private Guid serverGuid = Guid.Empty;
public FormServer()
{
InitializeComponent();
}
protected override void OnClosed(EventArgs e)
{
if (this.server != null)
{
this.server.Dispose();
}
base.OnClosed(e);
}
private void buttonStart_Click(object sender, EventArgs e)
{
this.serverGuid = Guid.NewGuid();
this.server = new BasicSocketServer();
this.server.ReceiveMessageEvent += new SocketServerLib.SocketHandler.ReceiveMessageDelegate(server_ReceiveMessageEvent);
this.server.ConnectionEvent += new SocketConnectionDelegate(server_ConnectionEvent);
this.server.CloseConnectionEvent += new SocketConnectionDelegate(server_CloseConnectionEvent);
this.server.Init(new IPEndPoint(IPAddress.Loopback, 2147));
this.server.StartUp();
this.buttonStart.Enabled = false;
this.buttonStop.Enabled = true;
this.buttonSend.Enabled = true;
MessageBox.Show("Server Started");
}
void server_CloseConnectionEvent(AbstractTcpSocketClientHandler handler)
{
MessageBox.Show(string.Format("A client is disconnected from the server"), "Socket Server", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
void server_ConnectionEvent(AbstractTcpSocketClientHandler handler)
{
MessageBox.Show(string.Format("A client is connected to the server"), "Socket Server", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
void server_ReceiveMessageEvent(SocketServerLib.SocketHandler.AbstractTcpSocketClientHandler handler, SocketServerLib.Message.AbstractMessage message)
{
BasicMessage receivedMessage = (BasicMessage)message;
byte[] buffer = receivedMessage.GetBuffer();
if (buffer.Length > 1000)
{
MessageBox.Show(string.Format("Received a long message of {0} bytes", receivedMessage.MessageLength), "Socket Server",
MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
string s = System.Text.ASCIIEncoding.Unicode.GetString(buffer);
this.SetReceivedText(s);
}
private void buttonStop_Click(object sender, EventArgs e)
{
this.server.Shutdown();
this.server.Dispose();
this.server = null;
this.buttonStart.Enabled = true;
this.buttonStop.Enabled = false;
this.buttonStop.Enabled = false;
MessageBox.Show("Server Stopped");
}
private void SetReceivedText(string text)
{
if (this.textBoxReceived.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetReceivedText);
this.Invoke(d, new object[] { text });
}
else
{
this.textBoxReceived.Text = text;
}
}
private void buttonSend_Click(object sender, EventArgs e)
{
ClientInfo[] clientList = this.server.GetClientList();
if (clientList.Length == 0)
{
MessageBox.Show("The client is not connected", "Socket Server", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
AbstractTcpSocketClientHandler clientHandler = clientList[0].TcpSocketClientHandler;
string s = this.textBoxSend.Text;
byte[] buffer = System.Text.ASCIIEncoding.Unicode.GetBytes(s);
BasicMessage message = new BasicMessage(this.serverGuid, buffer);
clientHandler.SendAsync(message);
}
}
}
The following is the nodejs client code.
var sys = require("sys"),
net = require("net");
var client = net.createConnection(2147);
client.setEncoding("UTF8");
client.addListener("connect", function() {
sys.puts("Client connected.");
// close connection after 2sec
setTimeout(function() {
sys.puts("Sent to server: close");
client.write("close", "UTF8");
}, 2000);
});
client.addListener("data", function(data) {
sys.puts("Response from server: " + data);
if (data == "close") client.end();
});
client.addListener("close", function(data) {
sys.puts("Disconnected from server");
});
I am able to solve the issue. This is just a overlook issue. In server code , I am using lan address assigned to my machine , but in client side , I am using 127.0.0.1 . when I changed the both to same value , I amnot getting econnrefused error.
Now I am able to send and receive data. However I am getting ECONNRESET error very frequently. any leads?
I have a problem with a small C# application.
The application has to connect through a serial port to a bar code scanner which reads a Data Matrix code. The Data Matrix code represents an array of bytes which is a zip archive. I read a lot about the way SerialPort.DataReceived work but I can't find an elegant solution to my problem. And the application should work with different bar code scanners so i can't make it scanner specific. Here is some of my code:
using System;
using System.IO;
using System.IO.Ports;
using System.Windows.Forms;
using Ionic.Zip;
namespace SIUI_PE
{
public partial class Form1 : Form
{
SerialPort _serialPort;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
_serialPort = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
}
catch (Exception ex)
{
MessageBox.Show("Error:" + ex.ToString());
return;
}
_serialPort.Handshake = Handshake.None;
_serialPort.ReadBufferSize = 10000;
_serialPort.DataReceived += new SerialDataReceivedEventHandler(comPort_DataReceived);
_serialPort.Open();
}
void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
byte[] data = new byte[10000];
_serialPort.Read(data, 0, 10000);
File.WriteAllBytes(Directory.GetCurrentDirectory() + "/temp/fis.zip", data);
try
{
using (ZipFile zip = ZipFile.Read(Directory.GetCurrentDirectory() + "/temp/fis.zip"))
{
foreach (ZipEntry ZE in zip)
{
ZE.Extract(Directory.GetCurrentDirectory() + "/temp");
}
}
File.Delete(Directory.GetCurrentDirectory() + "/temp/fis.zip");
}
catch (Exception ex1)
{
MessageBox.Show("Corrupt Archive: " + ex1.ToString());
}
}
}
}
So my question is: How can I know that I read all the bytes the scanner sent?
The code I've got for reading barcode data, which has been working flawlessly in production for several years looks like this:
Note, my app has to read standard UPC barcodes as well as GS1 DataBar, so there's a bit of code you may not need...
The key line in this is:
string ScanData = ScannerPort.ReadExisting();
which is found in the DoScan section, and simply reads the scan data as a string. It bypasses the need to know how many bytes are sent, and makes the rest of the code easier to deal with.
// This snippet is in the Form_Load event, and it initializes teh scanner
InitializeScanner();
ScannerPort.ReadExisting();
System.Threading.Thread.Sleep(1000);
// ens snippet from Form_Load.
this.ScannerPort.DataReceived += new SerialDataReceivedEventHandler(ScannerPort_DataReceived);
delegate void DoScanCallback(); // used for updating the form UI
void DoScan()
{
if (this.txtCouponCount.InvokeRequired)
{
DoScanCallback d = new DoScanCallback(DoScan);
this.Invoke(d);
return;
}
System.Threading.Thread.Sleep(100);
string ScanData = ScannerPort.ReadExisting();
if (isInScanMode)
{
try
{
HandleScanData(ScanData);
}
catch (Exception ex)
{
System.Media.SystemSounds.Beep.Play();
MessageBox.Show("Invalid Scan");
}
}
}
void ScannerPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
// this call to sleep allows the scanner to receive the entire scan.
// without this sleep, we've found that we get only a partial scan.
try
{
DoScan();
}
catch (Exception ex)
{
System.Media.SystemSounds.Beep.Play();
MessageBox.Show("Unable to handle scan event in ScannerPort_DataReceived." + System.Environment.NewLine + ex.ToString());
}
}
void Port_ErrorReceived(object sender, System.IO.Ports.SerialErrorReceivedEventArgs e)
{
System.Media.SystemSounds.Beep.Play();
MessageBox.Show(e.EventType.ToString());
}
private void HandleScanData(string ScanData)
{
//MessageBox.Show(ScanData + System.Environment.NewLine + ScanData.Length.ToString());
//Determine which type of barcode has been scanned, and handle appropriately.
if (ScanData.StartsWith("A") && ScanData.Length == 14)
{
try
{
ProcessUpcCoupon(ScanData);
}
catch (Exception ex)
{
System.Media.SystemSounds.Beep.Play();
MessageBox.Show("Unable to process UPC coupon data" + System.Environment.NewLine + ex.ToString());
}
}
else if (ScanData.StartsWith("8110"))
{
try
{
ProcessDataBarCoupon(ScanData);
}
catch (Exception ex)
{
System.Media.SystemSounds.Beep.Play();
MessageBox.Show("Unable to process DataBar coupon data" + System.Environment.NewLine + ex.ToString());
}
}
else
{
System.Media.SystemSounds.Beep.Play();
MessageBox.Show("Invalid Scan" + System.Environment.NewLine + ScanData);
}
}
private void InitializeScanner()
{
try
{
ScannerPort.PortName = Properties.Settings.Default.ScannerPort;
ScannerPort.ReadBufferSize = Properties.Settings.Default.ScannerReadBufferSize;
ScannerPort.Open();
ScannerPort.BaudRate = Properties.Settings.Default.ScannerBaudRate;
ScannerPort.DataBits = Properties.Settings.Default.ScannerDataBit;
ScannerPort.StopBits = Properties.Settings.Default.ScannerStopBit;
ScannerPort.Parity = Properties.Settings.Default.ScannerParity;
ScannerPort.ReadTimeout = Properties.Settings.Default.ScannerReadTimeout;
ScannerPort.DtrEnable = Properties.Settings.Default.ScannerDtrEnable;
ScannerPort.RtsEnable = Properties.Settings.Default.ScannerRtsEnable;
}
catch (Exception ex)
{
MessageBox.Show("Unable to initialize scanner. The error message received will be shown next. You should close this program and try again. If the problem persists, please contact support.", "Error initializing scanner");
MessageBox.Show(ex.Message);
Application.Exit();
}
}
As stated in the doc for SerialPort.DataReceived, "Use the BytesToRead property to determine how much data is left to be read in the buffer."
here is the doc for SerialPort.BytesToRead
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.bytestoread.aspx
I'm trying to read from a Uri which i created and to display it on windows phone 7 app.
(I'm doing this tutorial:http://msdn.microsoft.com/en-us/windowsmobile/Video/hh237494).
My problem is that the program doesnt get into the OpenReadCompletedEventHandler and i dont know why. (i putted message box in order to debug and i found out that the program doesnt get into the OpenReadCompletedEventHandler). Here is the relevant code:
void myButton_Click(object sender, RoutedEventArgs e)
{
try
{
WebClient webClient = new WebClient();
Uri uri = new Uri("http://localhost:44705/Service1.svc/GetAllBrands");
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
try
{
webClient.OpenWriteAsync(uri);
MessageBox.Show("opening sucsseded");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
MessageBox.Show("OpenRead Handler");
// OpenWriteCompletedEventArgs temp = (OpenWriteCompletedEventArgs)e;
DataContractJsonSerializer serializer = null;
try
{
serializer = new DataContractJsonSerializer(typeof(ObservableCollection<Brand>));
ObservableCollection<Brand> Brands = serializer.ReadObject(e.Result) as ObservableCollection<Brand>;
foreach (Brand b in Brands)
{
int id = b.BrandId;
string name = b.BrandName;
listBrands.Items.Add(id + " " + name);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Thanks in advance!
I have never used this but a quick google takes me to this page on MSDN - http://msdn.microsoft.com/en-us/library/system.net.webclient.openreadcompleted.aspx
This should tell you why it's not working - because you are using a read event for a write operation. You should be using OpenWriteCompletedEventHandler with OpenWriteAsync as per this page on MSDN - http://msdn.microsoft.com/en-us/library/system.net.webclient.openwritecompleted.aspx