Stream.Flush is not Flushing data in stream - c#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Sockets;
using InTheHand.Net.Ports;
using System.IO;
Guid muuid = new Guid("00001101-0000-1000-8000-00805F9B34FB");
private void scan()
{
UpdateUI("Starting Scan...");
BluetoothClient client = new BluetoothClient();
Devices = client.DiscoverDevicesInRange();
UpdateUI("Scan Complete");
foreach (BluetoothDeviceInfo d in Devices)
{
items.Add(d.DeviceName);
}
UpdateDeviceList();
}
private void StartScan()
{
lb_BT.DataSource = null;
lb_BT.Items.Clear();
items.Clear();
Thread bluetoothScanThread = new Thread(new ThreadStart(scan));
bluetoothScanThread.Start();
}
BluetoothDeviceInfo[] Devices;
private void UpdateDeviceList()
{
Func<int> del = delegate()
{
lb_BT.DataSource = items;
return 0;
};
Invoke(del);
}
BluetoothDeviceInfo deviceInfo;
private void ClientConnectThread()
{
BluetoothClient client = new BluetoothClient();
UpdateUI("Attempting connect");
client.BeginConnect(deviceInfo.DeviceAddress, muuid, this.BluetoothClientConnectCallback, client);
}
Stream stream = null;
public void BluetoothClientConnectCallback(IAsyncResult res)
{
{
BluetoothClient client = (BluetoothClient)res.AsyncState;
client.EndConnect(res);
stream = client.GetStream();
else
{
SetupObj.bInitialize(stream);
}
//fpcresp[0] = (byte)stream.ReadByte();
}
}
private void writeCmd(byte[] buffer)
{
try
{
stream.Flush();
stream.Write(buffer, 0, buffer.Length);
retCode = SUCCESS;
}
catch (Exception ex)
{
retCode = FAILURE;
Debug.WriteLine("Write IO Exception " + ex.Message);
}
}
private byte[] ReadCmd()
{
if( stream!= null)
{
byte[] BytesRead = new byte[100];
int BytesReadCnt = 0;
stream.Read(BytesRead, 0, 3);
return BytesRead;
}
else
{
return null;
}
}
First i will call writeCmd , then ReadCmd. Sometimes what is happening i am getting the unread data in ReadCmd.(because of last writeCmd) so i used stream.Flush(); before every writeCmd. then also the data on stream is not Flushing.

Related

Getting messy/croped on PictureBox by Socket Streaming C#

I am trying to get the printScreen from another device using socket.
My sending device (windowsce 6.0) code is
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Data;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
namespace ServerComputer
{
class Program
{
static Socket sendsocket;
enum RasterOperation : uint { SRC_COPY = 0x00CC0020 }
[DllImport("coredll.dll")]
static extern int BitBlt(IntPtr hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, RasterOperation rasterOperation);
[DllImport("coredll.dll")]
private static extern IntPtr GetDC(IntPtr hwnd);
[DllImport("coredll.dll")]
private static extern int ReleaseDC(IntPtr hwnd, IntPtr hdc);
public static void Main(string[] args)
{
Console.Out.WriteLine("Gildo Lindo Fon");
try
{
sendsocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//The instantiation of socket, IP for 192.168.1.106, 10001 for Port
IPEndPoint ipendpiont = new IPEndPoint(IPAddress.Parse("192.168.0.24"), 81);
sendsocket.Connect(ipendpiont);
//Establishment of end point
Console.Out.WriteLine("starting thread");
Thread th = new Thread(sendImageThread);
//th.IsBackground = true;
th.Start();
}
catch (Exception ee)
{
Console.Out.WriteLine(ee.Message);
return;
}
}
private static Bitmap GetScreen()
{
Rectangle bounds = Screen.PrimaryScreen.Bounds;
IntPtr hdc = GetDC(IntPtr.Zero);
Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format16bppRgb565);
using (Graphics graphics = Graphics.FromImage(bitmap))
{
IntPtr dstHdc = graphics.GetHdc();
BitBlt(dstHdc, 0, 0, bounds.Width, bounds.Height, hdc, 0, 0,RasterOperation.SRC_COPY);
graphics.ReleaseHdc(dstHdc);
}
ReleaseDC(IntPtr.Zero, hdc);
return bitmap;
}
private static void sendImageThread()
{
Console.Out.WriteLine("SENDING");
while (true)
{
try
{
MemoryStream ms = new MemoryStream();
Bitmap bitmapScreen = GetScreen();
bitmapScreen.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); //Here I use the BMP format
bitmapScreen.Save(".\\printimg.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] b = ms.ToArray();
sendsocket.Send(b);
ms.Close();
}
catch (Exception ee)
{
Console.Out.WriteLine(ee.Message);
break;
}
Thread.Sleep(1000);
}
}
}
}
My receiver code is like this:
using System.Net;
using System.Net.Sockets;
namespace httpScreenClient;
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Socket hostSocket = null!;
Thread thread = null!;
string localIP = string.Empty;
string computrHostName = string.Empty;
int dataSize = 0;
byte[] imageBytes = new byte[800 * 650 * 16*10]; //Picture of great 16 bpp RGB 565
private void mainForm_Load(object sender, EventArgs e)
{
computrHostName = Dns.GetHostName();
IPHostEntry hostname = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in hostname.AddressList)
{
if (ip.AddressFamily.ToString() == "InterNetwork")
{
localIP = ip.ToString();
}
}
this.Text = this.Text + " | " + localIP;
}
private void liveScreen_Click(object sender, EventArgs e)
{
connectSocket();
}
private void connectSocket()
{
Socket receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint hostIpEndPoint = new IPEndPoint(IPAddress.Parse("192.168.0.24"), 81);
//Connection node
receiveSocket.Bind(hostIpEndPoint);
receiveSocket.Listen(10);
//MessageBox.Show("start");
hostSocket = receiveSocket.Accept();
thread = new Thread(new ThreadStart(trreadimage))
{
IsBackground = true
};
thread.Start();
}
private void trreadimage()
{
while (true) {
string imageName = "stremScreen.JPG";
try
{
dataSize = hostSocket.Receive(imageBytes);
if (dataSize > 0)
{
MemoryStream ms = new MemoryStream(imageBytes);
Image img = Image.FromStream(ms);
img.Save(imageName, System.Drawing.Imaging.ImageFormat.Jpeg);
videoBox.Image = img;
ms.Close();
}
}
catch (Exception ee)
{
//messagebox.show("foi aqui - " + ee.message);
break;
}
Thread.Sleep(1500);
}
trreadimage();
}
}
I checked the screenprinted saved on the sending side and is alright, but what I getting on the receiver side is very messy, as there was some wrongs crops one over the other...
Streamed image received:
Do you guys have any suggest about what could be going on? actually I was getting the Image.FromStream() error too (https://social.msdn.microsoft.com/Forums/en-US/820fe38b-3fb6-4490-9608-10c4133e4a50/imagefromstreamms-parameter-is-not-valid?forum=aspdotnetwebpages) on the receiver side, that's why I left the catch {} part of the code empty... I didn't get to solve this error.
After some tries I got the solution by compressing the byte array before sending with
private static byte[] Compress(byte[] data)
{
MemoryStream output = new MemoryStream();
using (DeflateStream dstream = new DeflateStream(output, CompressionMode.Compress))
{
dstream.Write(data, 0, data.Length);
}
return output.ToArray();
}
And decompressing it on the other side with:
private static byte[] Decompress(byte[] data)
{
MemoryStream input = new MemoryStream(data);
MemoryStream output = new MemoryStream();
using (DeflateStream dstream = new DeflateStream(input, CompressionMode.Decompress))
{
dstream.CopyTo(output);
}
return output.ToArray();
}

How to receive data from Bluetooth device in C#

I'm trying to get data from BT device. I know that i can use InTheHand library for it in C#, but i can't connect to device and get data. I use sniffer and know that device work and send data. Maybe someone know how to work with BT in C#? I need only data from it, not send or etc.
I've got this code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using InTheHand.Net.Sockets;
using InTheHand.Net;
using InTheHand.Net.Bluetooth;
using InTheHand.Windows.Forms;
using System.Net.Sockets;
using System.Diagnostics;
using System.Threading;
namespace BLE{
static class Program
{
private static string sCode = "0000";
// My BT notebook
private static BluetoothEndPoint EP = new BluetoothEndPoint(BluetoothAddress.Parse("50:76:AF:99:D3:87"), BluetoothService.BluetoothBase);
private static BluetoothClient BC = new BluetoothClient(EP);
// The BT device that would connect
private static BluetoothDeviceInfo BTDevice = new BluetoothDeviceInfo(BluetoothAddress.Parse("34:29:F0:F4:49:C8"));
private static NetworkStream stream = null;
static void Main(string[] args)
{
if (BluetoothSecurity.PairRequest(BTDevice.DeviceAddress, sCode))
{
Console.WriteLine("PairRequest: OK");
if (BTDevice.Authenticated)
{
Console.WriteLine("Authenticated: OK");
BC.SetPin(sCode);
BC.BeginConnect(BTDevice.DeviceAddress, BluetoothService.SerialPort, new AsyncCallback(Connect), BTDevice);
}
else
{
Console.WriteLine("Authenticated: No");
}
}
else
{
Console.WriteLine("PairRequest: No");
}
Console.ReadLine();
}
private static void Connect(IAsyncResult result)
{
if (result.IsCompleted)
{
// client is connected now :)
Console.WriteLine(BC.Connected);
stream = BC.GetStream();
if (stream.CanRead)
{
byte[] myReadBuffer = new byte[1024];
StringBuilder myCompleteMessage = new StringBuilder();
int numberOfBytesRead = 0;
// Incoming message may be larger than the buffer size.
do
{
numberOfBytesRead = stream.Read(myReadBuffer, 0, myReadBuffer.Length);
for (int i = 0; i < numberOfBytesRead; i++)
myCompleteMessage.AppendFormat("0x{0:X2} ", myReadBuffer[i]);
}
while (stream.DataAvailable);
// Print out the received message to the console.
Console.WriteLine("You received the following message : " + myCompleteMessage);
}
else
{
Console.WriteLine("Sorry. You cannot read from this NetworkStream.");
}
Console.ReadLine();
}
}
}
}
In console i see "PairRequest: No"...
Can you help me to get the correct result?

Receive incomplete/wrong string over TCP

I´ve got a problem with my TCP client.
My TCP server sends a Bitmap as a String to the TCP client. At the moment there are 15 bmp per second. My Problem is, that most of them are read as "//////...." when I convert the received byte array to a string.
My TCP server code is (C#):
private void StreamWriter(byte[] writeMessage)
{
TcpClient client = new TcpClient();
client.Connect(IPAddress.Parse(Ip), Port);
NetworkStream streamSender = client.GetStream();
streamSender.Write(writeMessage, 0, writeMessage.Length);
streamSender.Flush();
streamSender.Close();
client.Close();
}
private void sendImage()
{
while (send)
{
MemoryStream mem = new MemoryStream();
image.Save(mem, System.Drawing.Imaging.ImageFormat.Bmp);
mem.Close();
mem.Dispose();
StreamWriter(Encoding.ASCII.GetBytes(Convert.ToBase64String(mem.ToArray())));
i++;
}
}
My client code is (Android Studio):
class MyServerThread implements Runnable {
#Override
public void run() {
try {
ServerSocket ss = new ServerSocket(50000);
while (true) {
Socket s = ss.accept();
InputStream is = (s.getInputStream());
BufferedInputStream bufferedReader = new BufferedInputStream(is);
byte[] contents = new byte[440000];
int bytesRead = 0;
while ((bytesRead = bufferedReader.read(contents)) != -1) {
message = new String(contents, 0, bytesRead);
}
is.close();
bufferedReader.close();
if (message.equals("Connection OK!")) {
createIP();
} else {
createPic();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I found a solution.
This is the client code now:
class MyServerThread implements Runnable {
#Override
public void run() {
try {
ServerSocket ss = new ServerSocket(50000);
while (true) {
Socket s = ss.accept();
InputStream is = (s.getInputStream());
BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
message = total.toString();
s.close();
is.close();
if (message.equals("Connection OK!")) {
createIP();
} else {
createPic();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

sending big file with socket to server c#

I'm trying to send a file about 250 kb to server but i have a corruption and it seemd that tottaly transfered some bytes only. The flow of command is
Write to stream: Send\r\n
Write to stream: FileName\r\n
Write to stream: FileData \r\n
Close the connection
Here is the code:
TcpClient sendClient = new TcpClient(serverName, port);
SslStream sendStream = new SslStream(sendClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
try
{
sendStream.AuthenticateAsClient(serverName, null, SslProtocols.Ssl2, true);
sendStream.Write(Encoding.UTF8.GetBytes("Login\r\n" + username + "\r\n" + password + "\r\n"));
sendStream.Flush();
int bytesResp = -1;
byte[] buffer = new byte[1026];
bytesResp = sendStream.Read(buffer, 0, buffer.Length);
string response = Encoding.UTF8.GetString(buffer, 0, bytesResp);
if (response.Trim() == "OK")
{
byte[] fileNameByte = Encoding.UTF8.GetBytes(fileName + "\r\n");
byte[] fileData = File.ReadAllBytes(filePath);
byte[] newLine = Encoding.ASCII.GetBytes("\r\n");
byte[] clientData = new byte[4 + Encoding.ASCII.GetBytes("Send\r\n").Length + fileNameByte.Length + fileData.Length+newLine.Length];
byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);
byte[] send = Encoding.ASCII.GetBytes("Send\r\n");
send.CopyTo(clientData, 0);
fileNameLen.CopyTo(clientData, 4 + send.Length);
fileNameByte.CopyTo(clientData, send.Length);
fileData.CopyTo(clientData, 4 + fileNameByte.Length + send.Length);
newLine.CopyTo(clientData, 4+ fileNameByte.Length + send.Length + fileData.Length);
MessageBox.Show(clientData.Length.ToString());
sendStream.Write(clientData, 0, clientData.Length);
sendStream.Flush();
sendStream.Write(Encoding.UTF8.GetBytes("Quit\r\n"));
sendClient.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Does anybody have an idea please?
You haven't told us about the other end of the connection, so this answer is partially speculative...
BitConverter.GetBytes(fileNameByte.Length); is likely to be a little-endian conversion.
Almost all network encoding will be big-endian, so this is a strong candidate for the failure.
I suggest you use the EndianBitConverter.Big converter from Jon Skeet's miscutil to get the proper encoding order.
I send file up to 1GB with this code
Server Code
using System;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.IO;
namespace Server_FileSend
{
public partial class Form1 : Form
{
Socket Server = null;
Socket Client = null;
Thread trStart;
Thread trRecive;
const int sizeByte = 1024;
public Form1()
{
InitializeComponent();
}
private void ReciveFile()
{
while (true)
{
try
{
byte[] b = new byte[sizeByte];
int rec = 1;
int vp = 0;
rec = Client.Receive(b);
int index;
for (index = 0; index < b.Length; index++)
if (b[index] == 63)
break;
string[] fInfo = Encoding.UTF8.GetString(b.Take(index).ToArray()).Split(':');
this.Invoke((MethodInvoker)delegate
{
progressBar1.Maximum = int.Parse(fInfo[0]);
});
string path = Application.StartupPath + "\\Downloads\\";
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
FileStream fs = new FileStream(path + fInfo[1], FileMode.Append, FileAccess.Write);
string strEnd;
while (true)
{
rec = Client.Receive(b);
vp = vp + rec;
strEnd = ((char)b[0]).ToString() + ((char)b[1]).ToString() + ((char)b[2]).ToString() + ((char)b[3]).ToString() + ((char)b[4]).ToString() + ((char)b[5]).ToString();
if (strEnd == "!endf!")
{
fs.Flush();
fs.Close();
MessageBox.Show("Receive File " + ((float)(float.Parse(fInfo[0]) / 1024)).ToString() + " KB");
break;
}
fs.Write(b, 0, rec);
this.Invoke((MethodInvoker)delegate
{
progressBar1.Value = vp;
});
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
Form1_FormClosing(null, null);
}
}
}
private void StartSocket()
{
Server.Listen(1);
Client = Server.Accept();
trRecive = new Thread(new ThreadStart(ReciveFile));
trRecive.Start();
}
private void Form1_Load(object sender, EventArgs e)
{
Server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
IPEndPoint IP = new IPEndPoint(IPAddress.Any, 5050);
Server.Bind(IP);
trStart = new Thread(new ThreadStart(StartSocket));
trStart.Start();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
trRecive.Abort();
trStart.Abort();
Environment.Exit(Environment.ExitCode);
}
catch (Exception)
{
Environment.Exit(Environment.ExitCode);
}
}
}
}
Client Code
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace Clienf_fileSend
{
public partial class Form1 : Form
{
Socket Client = null;
Thread trRecive;
const int sizeByte = 1024;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
IPEndPoint IP = new IPEndPoint(IPAddress.Parse(textBox1.Text), 5050);
Client.Connect(IP);
button1.Enabled = false;
button2.Enabled = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void SendFile(object FName)
{
try
{
FileInfo inf = new FileInfo((string)FName);
progressBar1.Invoke((MethodInvoker)delegate
{
progressBar1.Maximum = (int)inf.Length;
progressBar1.Value = 0;
});
FileStream f = new FileStream((string)FName, FileMode.Open);
byte[] fsize = Encoding.UTF8.GetBytes(inf.Length.ToString() + ":");
byte[] fname = Encoding.UTF8.GetBytes(inf.Name + "?");
byte[] fInfo = new byte[sizeByte];
fsize.CopyTo(fInfo, 0);
fname.CopyTo(fInfo, fsize.Length);
Client.Send(fInfo);
if (sizeByte> f.Length)
{
byte[] b = new byte[f.Length];
f.Seek(0, SeekOrigin.Begin);
f.Read(b, 0, (int)f.Length);
Client.Send(b);
}
else
{
for (int i = 0; i < (f.Length - sizeByte); i = i + sizeByte)
{
byte[] b = new byte[sizeByte];
f.Seek(i, SeekOrigin.Begin);
f.Read(b, 0, b.Length);
Client.Send(b);
progressBar1.Invoke((MethodInvoker)delegate
{
progressBar1.Value = i;
});
if (i + sizeByte >= f.Length - sizeByte)
{
progressBar1.Invoke((MethodInvoker)delegate
{
progressBar1.Value = (int)f.Length;
});
int ind = (int)f.Length - (i + sizeByte);
byte[] ed = new byte[ind];
f.Seek(i + sizeByte, SeekOrigin.Begin);
f.Read(ed, 0, ed.Length);
Client.Send(ed);
}
}
}
f.Close();
Thread.Sleep(1000);
Client.Send(Encoding.UTF8.GetBytes("!endf!"));
Thread.Sleep(1000);
MessageBox.Show("Send File " + ((float)inf.Length / 1024).ToString() + " KB");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog fdl = new OpenFileDialog();
if (fdl.ShowDialog() == DialogResult.OK)
{
trRecive = new Thread(new ParameterizedThreadStart(SendFile));
trRecive.Start(fdl.FileName);
}
fdl = null;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
trRecive.Abort();
Environment.Exit(Environment.ExitCode);
}
catch (Exception)
{
Environment.Exit(Environment.ExitCode);
}
}
}
}

Sockets: Only one usage of each socket address is normally permitted

I want to reuse a socket after I used it once, but I always get subj exception.
I found multiple questions with same issue but no working solution. I tried using code, i tried manual closing - but without any success
A little sample
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace SocketTest
{
class Program
{
static void Main()
{
for (int i = 1; i <= 2; i++)
{
var encoding = new UTF8Encoding(false);
var host = Dns.GetHostEntry("localhost");
var endpoint = new IPEndPoint(host.AddressList[0], 11322);
Console.WriteLine("Iteration #{0}\tEnpdoint = {1}", i, endpoint);
try
{
var client = new TcpClient(endpoint);
const string message = "Hello world!";
byte[] data = encoding.GetBytes(message);
client.Connect(endpoint);
var stream = client.GetStream();
stream.Write(data, 0, data.Length);
Console.WriteLine("Sent: {0}", message);
byte[] receiveData = new byte[4096];
int totalBytes = 0;
while (true)
{
int bytesRead = stream.Read(receiveData, 0, receiveData.Length);
totalBytes += bytesRead;
if (bytesRead < receiveData.Length)
break;
Array.Resize(ref receiveData, 2 * receiveData.Length);
}
var response = encoding.GetString(receiveData, 0, totalBytes);
Console.WriteLine("Received: {0}", response);
client.Client.Shutdown(SocketShutdown.Both);
client.Client.Disconnect(true);
stream.Close();
client.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.WriteLine();
}
}
}
}

Categories