I tried everything I could, but nothing works. My IP address 3 first digits changed from 192.168.1 to 192.168.0. The program has to accept data from address 192.168.0.255 then in reaction, it has to open a window and play video from a folder and is set to listen to every IP address there shouldn't be a problem before the change of router everything worked as expected.
For sending data I use my own android app I tested that app with Wireshark everything works as it should.
The window doesn't open everything works, but it seems that the socket just doesn't get any data.=>condition checking for available data socket available>0 returns false.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Timers;
using System.Net.Sockets;
using System.Net;
namespace SysConf
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
///
public partial class MainWindow : Window
{
Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
Timer timer1;
System.Windows.Threading.DispatcherTimer dispatcherTimer;
Encoding coding = Encoding.GetEncoding("ISO-8859-2");
int ByteC;
Byte[] bytes = new byte[1024];
EndPoint rE = new IPEndPoint(IPAddress.Any, 2200);
int order = 0;
public MainWindow()
{
InitializeComponent();
Clipboard.SetText(GetLocalIPAddress());
}
public static string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
if (ip.ToString().Split('.')[0] == "192")
{
return ip.ToString();
}
}
}
throw new Exception("No network adapters with an IPv4 address in the system!");
}
private void MainWindow1_StateChanged(object sender, EventArgs e)
{
if (MainWindow1.WindowState == WindowState.Maximized) { MainWindow1.WindowStyle = WindowStyle.None; }
else { MainWindow1.WindowStyle= WindowStyle.SingleBorderWindow; }
}
private void MainWindow1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.F11)
{
if (MainWindow1.WindowState == WindowState.Maximized)
{
MainWindow1.WindowState = WindowState.Normal;
MainWindow1.Topmost = false;
}
else
{
MainWindow1.WindowState = WindowState.Maximized;
MainWindow1.Topmost = true;
}
}
}
private void MainWindow1_Loaded(object sender, RoutedEventArgs e)
{
// win = (SysConf.MainWindow)Application.Current.MainWindow;
dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += dispatcherTimer_Tick;
dispatcherTimer.Interval = TimeSpan.FromMilliseconds(10);
dispatcherTimer.Start();
// MainWindow1.Visibility = Visibility.Collapsed;
MainWindow1.Visibility = Visibility.Collapsed;
if (GetLocalIPAddress() != "No network adapters with an IPv4 address in the system!")
{
sck.Bind(new IPEndPoint(IPAddress.Parse(GetLocalIPAddress()), 2200));
}
else
{
MessageBox.Show("No Internet connection!");
}
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
if (player1.Position == player1.NaturalDuration & MainWindow1.Visibility == Visibility.Visible)
{
MainWindow1.Topmost = false;
MainWindow1.Visibility = Visibility.Collapsed;
}
Task.Run(() =>
{
if (sck.Available > 0)
{
MessageBox.Show("Data arrived");
ByteC = sck.ReceiveFrom(bytes, ref rE);
order = 1;
}
});
if (order == 1)
{
this.Close();
String cmd = coding.GetString(bytes);
MainWindow1.Visibility = Visibility.Visible;
MainWindow1.Topmost = true;
player1.Source = new Uri("Resources/" + (cmd.Substring(0,12)).Split('_')[1] + ".mp4", UriKind.Relative); //+ (#"\Resources\" ), UriKind.Relative);
player1.Position = TimeSpan.Zero;
MainWindow1.WindowState = WindowState.Maximized;
player1.Play();
order = 0;
bytes = null;
bytes = new byte[9024];
cmd = "";
}
dispatcherTimer.Start();
}
private void timer1_Elapsed(object sender, ElapsedEventArgs e)
{
//win.Visibility = Visibility.Visible;
timer1.Start();
}
private void player1_BufferingEnded(object sender, RoutedEventArgs e)
{
}
}
}
Related
I wrote a code to update DDNS which works fine. I now need to run this code every n minutes: how would I go doing that?
I tried using:
while (true)
{
this.DoMyMethod();
Thread.Sleep(TimeSpan.FromMinutes(1));
}
and I am still having some trouble. What is the best way to run this task every n minutes?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Windows.Forms;
using System.Timers;
namespace GoogleDDNS
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (username.Text == "")
{
System.Windows.MessageBox.Show("Please enter the username");
username.Focus();
return;
}
if (password.Text == "")
{
System.Windows.MessageBox.Show("Please enter the password");
password.Focus();
return;
}
if (subdomain.Text == "")
{
System.Windows.MessageBox.Show("Please enter the subdomain");
subdomain.Focus();
return;
}
var client = new WebClient { Credentials = new NetworkCredential(username.Text, password.Text) };
var response = client.DownloadString("https://domains.google.com/nic/update?hostname=" + subdomain.Text);
responseddns.Content = response;
Properties.Settings.Default.usernamesave = username.Text;
Properties.Settings.Default.passwordsave = password.Text;
Properties.Settings.Default.subdomainsave = subdomain.Text;
Properties.Settings.Default.Save();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
username.Text = Properties.Settings.Default.usernamesave;
password.Text = Properties.Settings.Default.passwordsave;
subdomain.Text = Properties.Settings.Default.subdomainsave;
}
}
}
Why not using System.Threading.Timer to do so?
From the Microsoft documentation, say you have the following sample class:
class StatusChecker
{
private int invokeCount;
private int maxCount;
public StatusChecker(int count)
{
invokeCount = 0;
maxCount = count;
}
// This method is called by the timer delegate.
public void CheckStatus(Object stateInfo)
{
AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
Console.WriteLine("{0} Checking status {1,2}.",
DateTime.Now.ToString("h:mm:ss.fff"),
(++invokeCount).ToString());
if (invokeCount == maxCount)
{
// Reset the counter and signal the waiting thread.
invokeCount = 0;
autoEvent.Set();
}
}
}
Then you can create a Timer to run CheckStatus every n seconds, like:
// Create an AutoResetEvent to signal the timeout threshold in the
// timer callback has been reached.
var autoEvent = new AutoResetEvent(false);
var statusChecker = new StatusChecker(5);
// creates a Timer to call CheckStatus() with autoEvent as argument,
// starting with 1 second delay and calling every 2 seconds.
var stateTimer = new Timer(statusChecker.CheckStatus, autoEvent, 1000, 2000);
autoEvent.WaitOne();
i use timer,
the code is
using System;
using System.Net;
using System.Timers;
static void Main(string[] args)
{
Console.WriteLine("The system is start at {0}", DateTime.Now);
Timer t = new Timer(10000);
t.Enabled = true;
t.Elapsed += T_Elapsed;
Console.ReadKey();
}
private static void T_Elapsed(object sender, ElapsedEventArgs e)
{
//write your code
}
This is what fixed for me.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Windows.Forms;
using System.Timers;
namespace GoogleDDNS
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (username.Text == "")
{
System.Windows.MessageBox.Show("Please enter the username");
username.Focus();
return;
}
if (password.Text == "")
{
System.Windows.MessageBox.Show("Please enter the password");
password.Focus();
return;
}
if (subdomain.Text == "")
{
System.Windows.MessageBox.Show("Please enter the subdomain");
subdomain.Focus();
return;
}
var client = new WebClient { Credentials = new NetworkCredential(username.Text, password.Text) };
var response = client.DownloadString("https://domains.google.com/nic/update?hostname=" + subdomain.Text);
//MessageBox.Show(response);
responseddns.Content = response;
Properties.Settings.Default.usernamesave = username.Text;
Properties.Settings.Default.passwordsave = password.Text;
Properties.Settings.Default.subdomainsave = subdomain.Text;
//Properties.Settings.Default.intervalsave = interval.Text;
Properties.Settings.Default.Save();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
username.Text = Properties.Settings.Default.usernamesave;
password.Text = Properties.Settings.Default.passwordsave;
subdomain.Text = Properties.Settings.Default.subdomainsave;
//interval.Text = Properties.Settings.Default.intervalsave;
System.Windows.Forms.Timer MyTimer = new System.Windows.Forms.Timer();
MyTimer.Interval = (1 * 60 * 1000); // 45 mins
MyTimer.Tick += new EventHandler(MyTimer_Tick);
MyTimer.Start();
}
private void MyTimer_Tick(object sender, EventArgs e)
{
var client = new WebClient { Credentials = new NetworkCredential(username.Text, password.Text) };
var response = client.DownloadString("https://domains.google.com/nic/update?hostname=" + subdomain.Text);
//MessageBox.Show(response);
responseddns.Content = response;
//this.Close();
}
}
}
Have a look at this. I recall a colleague using it a while ago:
FluentScheduler - [Project Site]
Usage:
// Schedule an IJob to run at an interval
Schedule<MyJob>().ToRunNow().AndEvery(2).Minutes();
Will fulfill your need.
somwhere met this code
class Program
{
static void Main(string[] args)
{
int Interval = 5;
CancellationTokenSource cancellation = new CancellationTokenSource();
Console.WriteLine("Start Loop...");
RepeatActionEvery(() => Console.WriteLine("Hi time {0}",DateTime.Now), TimeSpan.FromMinutes(Interval), cancellation.Token).Wait();
Console.WriteLine("Finish loop!!!");
}
public static async Task RepeatActionEvery(Action action, TimeSpan interval, CancellationToken cancellationToken)
{
while (true)
{
action();
Task task = Task.Delay(interval, cancellationToken);
try
{
await task;
}
catch (TaskCanceledException)
{
return;
}
}
}
}
New to WinForms but not ASP.NET or C#. Trying to make client/server app. Successfully received data from client on server but having troubles displaying it on server program winform. Codes are:
Server App code:
using System;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
namespace Server_App
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
IPEndPoint ep = new IPEndPoint(IPAddress.Loopback, 1234); //configure host
TcpListenerEx listener = new TcpListenerEx(ep); //set host to listen
if (!listener.Active)
{
listener.Start();
}
while (true)
{
const int byteSize = 1024 * 1024;
byte[] message = new byte[byteSize];
var s = listener.AcceptTcpClient();
s.GetStream().Read(message, 0, byteSize); //obtaining network stream and receiving data through .Read()
message = cleanMessage(message);
string g = System.Text.Encoding.UTF8.GetString(message);
addMessage(g);
}
}
private void addMessage(string m)
{
this.textBox1.Text = textBox1.Text + Environment.NewLine + " >> " + m;
}
private byte[] cleanMessage(byte[] rawMessageByte)
{
byte[] cleanMessage = rawMessageByte.Where(b => b != 0).ToArray();
return cleanMessage;
}
}
}
Client App code:
using System;
using System.Net.Sockets;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ClientApp
{
public partial class ClientApp : Form
{
public ClientApp()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var message = System.Text.Encoding.UTF8.GetBytes(txtFromClient.Text);
using (var client = new TcpClient("127.0.0.1", 1234))//make connection with the host
{
NetworkStream stream = client.GetStream();/*obtain network stream*/
stream.Write(message, 0, message.Length);
}
}
private void textBox1_Click(object sender, EventArgs e)
{
txtFromClient.Text = "";
}
}
}
Everything is happening as planned except for displaying received data on server program's Form1's textbox. On debugging, I confirmed the correct value received in variable m of line this.textBox1.Text = textBox1.Text + Environment.NewLine + " >> " + m;. Only problem is that this value cannot be displayed and hence seen on the Form1 of server program.
With the help and guidance from #AdrianoRepetti, solution to the given problem was furnished through the following code:
using System;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Linq;
namespace Server_App
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
backgroundWorker1.WorkerReportsProgress = true;
}
private void button1_Click(object sender, EventArgs e)
{
IPEndPoint ep = new IPEndPoint(IPAddress.Loopback, 1234); //configure host
if(!backgroundWorker1.IsBusy)
{
backgroundWorker1.RunWorkerAsync(ep); //called to start a process on the worker thread and send argument (listener) to our workerprocess.
}
}
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
IPEndPoint ep = e.Argument as IPEndPoint;
TcpListenerEx listener = new TcpListenerEx(ep);
if (!listener.Active)
{
listener.Start();
}
while (true)
{
try
{
const int byteSize = 1024 * 1024;
byte[] message = new byte[byteSize];
using (var s = listener.AcceptTcpClient())
{
s.GetStream().Read(message, 0, byteSize);//obtaining network stream and receiving data through .Read()
message = cleanMessage(message);
string g = System.Text.Encoding.UTF8.GetString(message);
backgroundWorker1.ReportProgress(0, g);
}
}
catch (Exception ex)
{
backgroundWorker1.ReportProgress(0, ex.Message);
}
finally
{
listener.Stop();
}
}
}
private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
textBox1.AppendText(Environment.NewLine + ">> " + e.UserState);
}
private byte[] cleanMessage(byte[] rawMessageByte)
{
byte[] cleanMessage = rawMessageByte.Where(b => b != 0).ToArray();
return cleanMessage;
}
}
}
Hope it helps.
I have tried 2 of how to make multi client, which is multi thread and asynchronous server. Both didn't work for me. The multi thread can make client send broadcast to all client, but some of them didn't receive the broadcasted data. While the asynchronous server cannot make the client connect too long. I don't know whether it's my code that's wrong or what. Please help me based on my latest working code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace Server
{
public partial class Form1 : Form
{
private TcpClient client;
public StreamReader STR;
public StreamWriter STW;
public string receive;
public String text_to_send;
public Form1()
{
InitializeComponent();
IPAddress[] localIP = Dns.GetHostAddresses(Dns.GetHostName()); //Using the PC's IP
foreach (IPAddress address in localIP) {
if (address.AddressFamily == AddressFamily.InterNetwork) {
textBox5.Text = address.ToString();
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e) //Button to start the server
{
TcpListener listener = new TcpListener(IPAddress.Any, int.Parse(textBox6.Text));
listener.Start();
client = listener.AcceptTcpClient();
STR = new StreamReader(client.GetStream());
STW = new StreamWriter(client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync(); //Start receiving data in the background
backgroundWorker2.WorkerSupportsCancellation = true; //Cancel the active thread
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) //Receiving data
{
while(client.Connected)
{
try
{
receive = STR.ReadLine();
this.textBox2.Invoke(new MethodInvoker(delegate() { textBox2.AppendText("You : " + receive + "\n Received : " + receive.Length.ToString() + " byte. \n"); }));
receive = "";
}
catch(Exception x)
{
MessageBox.Show(x.Message.ToString());
}
}
}
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) //Sending data
{
if (client.Connected)
{
STW.WriteLine(text_to_send);
this.textBox2.Invoke(new MethodInvoker(delegate() { textBox2.AppendText("Me : " + text_to_send + "\n Sent : " + text_to_send.Length.ToString() + " byte \n"); }));//Text that will appeared on the screen after we enter the text that we type
}
else
{
MessageBox.Show("Send Failed!");
}
backgroundWorker2.CancelAsync();
}
private void button3_Click(object sender, EventArgs e) //Connected as client
{
client = new TcpClient();
IPEndPoint IP_End = new IPEndPoint(IPAddress.Parse(textBox3.Text), int.Parse(textBox4.Text));
try
{
client.Connect(IP_End);
if (client.Connected) {
textBox2.AppendText("Connected to server" + "\n");
STW = new StreamWriter(client.GetStream());
STR = new StreamReader(client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync(); //Start receiving data in the background
backgroundWorker2.WorkerSupportsCancellation = true; //Cancel the active thread
}
}
catch(Exception x)
{
MessageBox.Show(x.Message.ToString());
}
}
private void button1_Click(object sender, EventArgs e) //Send button
{
if (textBox1.Text != "")
{
text_to_send = textBox1.Text;
backgroundWorker2.RunWorkerAsync();
}
textBox1.Text = "";
}
private void label1_Click(object sender, EventArgs e)
{
}
}
}
N.B : Just translated the comment into English
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Hey guys I am new at the subject of Sockets
and I really need you help.
I am doing system of server and clients (like chat)
but something diffrent, I am doing it with Windows Form Application
in my server : I have list of sockets of all pepole that connect to the server, that already get acception from the server.
And I wanna to do a Timer that every X seconds it will runs on my List and check if the person is still connection I mean in that , that the person still connect on the internet and still can get packages and if not to remove him from the list.
someone can help me in c# how do it??
now at the server if someone is Exit the program Or if the internet is logout how i can check if the Client is out
and if yes so Close his connection?
i Read about TimeOut but how use it??? if it usfull?
Server:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Server
{
public partial class Form1 : Form
{
Socket sck;
static List<Socket> acc;
static List<Thread> thr;
//List<UserAt> thr;
static int port = 9000;
static IPAddress ip;
static Thread NewCon;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
acc = new List<Socket>();
//thr = new List<UserAt>();
thr = new List<Thread>();
NewCon = new Thread(getNewConnection);
//Console.WriteLine("please enter your host port ");
string inputPort = "9000";
try
{
port = Convert.ToInt32(inputPort);
}
catch
{
port = 9000;
}
ip = IPAddress.Parse("127.0.0.1");
sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sck.Bind(new IPEndPoint(ip, port));
sck.Listen(0);
NewCon.Start();
}
/// <summary>
/// get new connection from client
/// </summary>
public void getNewConnection()
{
while (true)
{
acc.Add(sck.Accept());
var t = new Thread(() => ReciveMessage(acc.Count-1));
t.Start();
thr.Add(t);
/* UserAt a = new UserAt();
a.index = acc.Count - 1;
a.thread = new Thread(() => ReciveMessage(a.index));
a.thread.Start();
thr.Add(a);
* */
}
}
public void ReciveMessage(int index)
{
while (true)
{
try
{
Thread.Sleep(500);
byte[] Buffer = new byte[255];
int rec = acc[index].Receive(Buffer, 0, Buffer.Length, 0);
Array.Resize(ref Buffer, rec);
//MessageBox.Show(Encoding.Default.GetString(Buffer));
//listBox1.Items.Add(Encoding.Default.GetString(Buffer));
SetText(Encoding.Default.GetString(Buffer));
}
catch
{
// thr[index].thread.Abort();
/*thr.RemoveAt(index);
for (int i = index+1; i < thr.Count;i++ )
{
thr[i].index -= 1;
}*/
break;
}
}
}
delegate void SetTextCallback(string text);
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.listBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.listBox1.Items.Add(text);
}
}
public string getIp()
{
IPHostEntry host;
string localIP = "?";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
localIP = ip.ToString();
}
}
return localIP;
}
}
}
Client
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Client
{
public partial class Form1 : Form
{
static string name = "";
static int port = 9000;
static IPAddress ip;
static Socket sck;
public Form1()
{
InitializeComponent();
}
public void ReciveMessage()
{
while (true)
{
Thread.Sleep(500);
byte[] Buffer = new byte[255];
int rec = sck.Receive(Buffer, 0, Buffer.Length, 0);
Array.Resize(ref Buffer, rec);
SetText(Encoding.Default.GetString(Buffer));
//MyChat.Items.Add(Encoding.Default.GetString(Buffer));
}
}
delegate void SetTextCallback(string text);
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.MyChat.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.MyChat.Items.Add(text);
}
}
private void Login_Click(object sender, EventArgs e)
{
name = UserName.Text;
ip = IPAddress.Parse("127.0.0.1");
string inputPort = "9000";
try
{
port = Convert.ToInt32(inputPort);
}
catch
{
port = 9000;
}
try
{
sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sck.Connect(new IPEndPoint(ip, port));
ReciveMes.Enabled = true;
byte[] conmsg = Encoding.Default.GetBytes("<" + name + ">" + " connected");
sck.Send(conmsg, 0, conmsg.Length, 0);
SendToServer.Enabled = true;
}
catch
{
MessageBox.Show("חיבור נכשל");
}
}
private void SendToServer_Click(object sender, EventArgs e)
{
byte[] sdata = Encoding.Default.GetBytes("<" + name + ">" + MyMessage.Text);
sck.Send(sdata, sdata.Length, 0);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if(SendToServer.Enabled)
{
byte[] sdata = Encoding.Default.GetBytes("<" + name + ">" + "Is Quit");
sck.Send(sdata, sdata.Length, 0);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO.Ports;
using System.Threading;
using System.Windows.Threading;
using System.Data.SQLite;
namespace Datalogging
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public class ThreadExample
{
public static void ThreadJob(MainWindow mainWindow)
{
string dBConnectionString = #"Data Source = C:\Users\johnmark\Documents\Visual Studio 2012\Projects\SerialTrial\SerialTrial\bin\Debug\employee.sqlite;";
SQLiteConnection sqliteCon = new SQLiteConnection(dBConnectionString);
//open connection to database
try
{
sqliteCon.Open();
SQLiteCommand createCommand = new SQLiteCommand("Select empID from EmployeeList", sqliteCon);
SQLiteDataReader reader;
reader = createCommand.ExecuteReader();
//richtextbox2.Document.Blocks.Clear();
while (reader.Read())
{
string Text = (String.Format("{0}", Object.Equals(definition.buffering, reader.GetValue(0))));
if (Convert.ToBoolean(Text))
{
mainWindow.SerialWrite('s');
Console.WriteLine(Text);
//richtextbox1.Document.Blocks.Add(new Paragraph(new Run(Text)));
}
}
sqliteCon.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
public partial class MainWindow : Window
{
//string received_data;
//Thread readThread = new Thread(Read);
FlowDocument mcFlowDoc = new FlowDocument();
Paragraph para = new Paragraph();
SerialPort serial = new SerialPort();
public MainWindow()
{
InitializeComponent();
combobox1.Items.Insert(0, "Select Port");
combobox1.SelectedIndex = 0;
string[] ports = null;
ports = SerialPort.GetPortNames();
// Display each port name to the console.
int c = ports.Count();
for (int i = 1; i <= c; i++)
{
if (!combobox1.Items.Contains(ports[i - 1]))
{
combobox1.Items.Add(ports[i - 1]);
}
}
}
private void combobox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void Button_Click(object sender, RoutedEventArgs e)
{
try
{
if ((string)button2.Content == "Connect")
{
string myItem = combobox1.SelectedItem.ToString();
if (myItem == "Select Port")
{
MessageBox.Show("Select Port");
}
else
{
serial.PortName = myItem;
serial.Open();
button2.Content = "Disconnect";
textbox2.Text = "Serial Port Opened";
serial.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived);
}
}
else
{
serial.Close();
button2.Content = "Connect";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
#region Receiving
public void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int bytes = serial.BytesToRead;
byte[] buffer = new byte[bytes];
serial.Read(buffer, 0, bytes);
foreach (var item in buffer)
{
Console.Write(item.ToString());
}
definition.buffering = BitConverter.ToInt64(buffer, 0);
Console.WriteLine();
Console.WriteLine(definition.buffering);
Console.WriteLine();
Thread thread = new Thread(new ThreadStart(ThreadExample.ThreadJob(this)));
thread.Start();
thread.Join();
}
#endregion
public void WriteSerial(string text)
{
serial.Write(text);
}
}
}
Hi guys. Can anyone help me what went wrong in this code? It is displaying this error:
Error 2 'Datalogging.MainWindow' does not contain a definition for 'SerialWrite' and no extension method 'SerialWrite' accepting a first argument of type 'Datalogging.MainWindow' could be found (are you missing a using directive or an assembly reference?)
Error 3 Method name expected
how can I fix that? Please edit the code and post it here as your answer thanks.
Change your method call mainWindow.SerialWrite('s'); to mainWindow.WriteSerial('s'); to fit the method name declared here :
public void WriteSerial(string text)
You inverted both words.
For your "Method name expected", I guess it's in port_DataReceived. You need to pass a delegate to the thread, but you're not doing it correctly.
Instead of
Thread thread = new Thread(new ThreadStart(ThreadExample.ThreadJob(this)));
(you can't directly pass a method as a parameter, you can only use function pointers) you can use this syntax to pass a delegate :
Thread thread = new Thread(new ThreadStart(() => ThreadExample.ThreadJob(this)));
Please note that new TreadStart is redundant, new Thread(() => ThreadExample.ThreadJob(this)); will do the job.