C # basic notes (16th days ),
1. Process Review
// Open the application through the process
Process. Start ("calc ");
Process. Start ("mspaint ");
Process. Start ("notepad ");
Process. Start ("iexplore", "http://www.baidu.com ");
// Open a specified file through a process
ProcessStartInfo psi = new ProcessStartInfo (@ "C: \ Users \ SJD \ Desktop \ AE .txt ");
Process p = new Process ();
P. StartInfo = psi;
P. Start ();
// What is the relationship between processes and threads? A process contains multiple threads
A single thread is easy to pretend to be a program.
// Foreground background
Thread
Thread th = new Thread (Test); Create a Thread
Th. IsBcakground = true; mark it as a background thread
Start () start thread (tell the CPU that I have prepared for execution, but the specific execution time is determined by the CPU)
Abort () terminate a thread (start () cannot be used again after termination ())
Thread. sleep (1) static method can stop the current thread for a period of time
// How to access controls in threads
The program does not allow cross-thread access, and an exception is thrown.
If you do not want to throw an exception, cancel the cross-Thread Check during program loading.
Although it is still not allowed to do so, it does not know this thing if it does not let it check.
Control. checkforillegalcrossthreadcils = false;
// Passing parameters through methods in the thread
If the method to be executed by a thread requires a parameter, the parameter must be of the object type.
And the parameter is passed to the called start ().
2. socket
Computers, telephones between programs send and receive data
Protocol for communication between people in two different places in Mandarin
Default language for communication between computer and computer
Common protocols: UDP and TCP
Socket hole, which acts as a process communication mechanism, also known as "socket", used to describe IP addresses and ports
It is the handle of a communication chain (actually used for communication between two programs)
The IP address is the connection server, and the port number is the connection application.
There must be a listening socket on the server to check whether a client is connected to our server.
The socket responsible for listening creates a socket responsible for communication
3. tcp and udp protocols
To connect the client to the server, you must first send a request
You must know the IP address of the server and the port number of the server application.
You can connect to the application on the server accurately.
TCP is safer and more stable than UDP, and data is generally not lost.
TCP Three handshake server (required) requests (must be sent from the client to the server)
Request client ---> server are you free?
Server ---> client I am free
Client ---> server I know you are free
The three-way handshake is successful, and the client sends and receives data with the server. Otherwise, no data communication will be conducted.
Secure, stable, and less efficient
UDP is fast and efficient, but unstable, and prone to data loss.
The customer service sends a message to the server. no matter whether the server is free or not, all the messages are sent. Whether the server has the energy to accept these messages, the anti-virus has passed.
UDP (video chat) for video transmission is not clear but smooth, but the screen is not clear, but one card and one card
3. Create a socket for communication with the client
Private void btnStart_Click (object sender, EventArgs e)
{
// When you click Start listening, create a Socket on the server that monitors the IP address and port number.
Socket socketWatch = new Socket (AddressFamily. InterNetwork, SocketType. Stream, ProtocolType. Tcp );
IPAddress ip = IPAddress. Any; // IPAddress. Parse (txtServer. Text );
// Create a port number object
IPEndPoint point = new IPEndPoint (ip, Convert. ToInt32 (txtPort. Text ));
// Listen
SocketWatch. Bind (point );
ShowMsg ("listener successful ");
** Set a listener queue
Sets the maximum number of listeners on the server.
// 10 people at a time point, and 11 people will queue up
SocketWatch. Listen (10 );
Thread th = new Thread (Listen );
Th. IsBackground = true;
Th. Start (socketWatch );
}
/// <Summary>
/// Wait for the client connection and create a socket to communicate with it
/// </Summary>
Void Listen (object o)
{
Socket socketWatch = o as Socket;
// Wait for the client connection and create a socket for communication
While (true)
{
Socket socketSend = socketWatch. Accept ();
// 192.168.1.50: Connection successful
ShowMsg (socketSend. RemoteEndPoint. ToString () + ":" + "connection successful ");
}
}
Void ShowMsg (string str)
{
TxtLog. AppendText (str + "\ r \ n ");
}
Private void Form1_Load (object sender, EventArgs e)
{
Control. CheckForIllegal
Crossthreadcils = false;
}
4. Design Protocol
Transfer files
How to determine whether the received data is a file or a text
Design "protocol ":
Add a byte before the byte array to be passed as the identifier. 0: indicates text. 1: Mark the file.
Text: 0 + text (byte array)
File: binary information of 1 + files
Convert a generic set to an array
Byte [] buffer = System. Text. Encoding. UTF8.GetBytes (str );
List <byte> list = new List <byte> ();
List. Add (0 );
List. AddRange (buffer );
Byte [] newBuffer = list. ToArray ();
5. Create Process notes for communications between the server and the client
Client Server
Socket ()
Bind () to Bind the listening port
Listen () sets the listener queue
While (true)
{
Connect () connection establish Accept () loop wait for client connection
}
Send () Send data Receive () Receive client information cyclically
Receive () Receive data Send ()
Close () send data capture exception Close ()
1. Create a general interface for the server
Row 1 txtServer (input IP address) txtPort (input port) btnStart (start listening) cboUsers (store connected IP address and port, combobox control)
Row 2 txtLog (display communication results)
Row 3 txtMsg (input communication information)
Row 4 txtPath (storing and displaying transmitted files and paths) btnSelect (selection) btnSendFile (sending files)
Row 5 btnSend (send message) btnZD (vibrate)
2. Enter the btnStart entry (click to start listening for execution)
When you click Start listening, create a socket on the server that monitors IP addresses and port numbers.
Socket socketWatch = new Socket (AddressFamily. InterNetwork, SocketType. Stream, ProtocolType. Tcp );
IPAddress ip = IPAddress. Any; // IPAddress. Parse (txtServer. Text );
Create a port object to splice the IP address and port number
IPEndPoint point = new IPEndPoint (ip, Convert. ToInt32 (txtPort. Text ));
Listeners
SocketWatch. Bind (point );
3. Create a method, prompt that the listener is successful, and assign the value to txtLog. Text.
Method to input a string parameter, indicating that the listener is successful
In addition, text will not be overwritten during each transmission only when the append mode is used.
+ \ R \ n next to text
Void ShowMsg (string str)
{
TxtLog. AppendText (str + "\ r \ n ");
}
4. Use the ShowMsg method to transmit "listener successful"
ShowMsg ("listener successful ");
5. Continue In btnStart
* ShowMsg ("listener succeeded ");
* Only 10 listening queues can be connected.
SocketWatch. Listen (10 );
* Wait for the client to connect and create a socket for communication
Socket socketSend = socketWatch. Accept (); socketWatch. Accept is the communication between the connected client.
* RemoteEndPoint can obtain the remotely connected IP address and port and output it to txtLog.
ShowMsg (socketSend. RemoteEndPoint. ToString () + ":" + "connection successful ");
6. Two Problems
1. The program is suspended because only one master thread runs.
Thread-based solution
2. Because only one client can connect to the received communication once
Write in a loop to solve the problem
7. Create a method to wait for the client connection and create a socket for communication with it
Void Listen ()
{
Cut the two rows in step 1
** SocketWatch does only one thing. It is accepted after listening.
Socket socketSend = socketWatch. Accept ();
ShowMsg (socketSend. RemoteEndPoint. ToString () + ":" + "connection successful ");
}
Add while (true) outside)
{
}
The socketWatch responsible for listening cannot be accessed.
The method has step 2. Step 2nd socketWatch declared outside
2. Pass socketWatch in
Parameter passing across threads can only be of the object Type
Use the second
Input a declared object type parameter o
Void Listen (object o)
Convert o of object type to Socket socketWatch
Socket socketWatch = o as Socket;
8. The Listen function will not be suspended until it is executed by a new thread.
Create a thread in the btnStart method and put the Listen method in it.
Thread th = new Thread (Listen );
Set as background thread
Th. IsBackground = true;
Run and input socketWatch to the Listen Function
Th. Start (socketWatch );
9. The program reports an error. When the program is loaded, the cross-thread error is canceled.
Private void Form1_Load (object sender, EventArgs e)
{
Control. checkforillegalcrossthreadcils = false;
}
Use telnet to test the connection status
10. Continue writing in the while loop in Step 7
After the client is successfully connected, the server should receive messages from the client.
Handling through the socket responsible for communication
** Use socket socketSend for communication with the client to send and receive data
The receive method accepts messages sent from the client and byte arrays.
Put the data in a byte array.
Byte [] buffer = new byte [1024*1024*2];
R is the actual number of valid bytes received
Int r = socketSend. Receive (buffer );
Converts the passed byte [] to a readable string.
String str = Encoding. UTF8.GetString (buffer, 0, r );
Output to the txtLog text box and call the previous method ShowMsg.
ShowMsg is used as the output text box (automatic line feed)
SocketSend. RemoteEndPoint indicates the IP address and port number of the client.
. Tostring indicates that the string type is converted. PASS Parameters to ShowMsg () as a whole string type together with the following ();
Display the data sent by the client on txtLog
ShowMsg (socketSend. RemoteEndPoint. ToString () + ":" + str );
11. After the test, it is found that only one number can be transferred. Therefore, it is necessary to write data cyclically and encapsulate the data.
Encapsulated as a method for receiving client information
Void Recive ()
{
While (true)
{
Byte [] buffer = new byte [1024*1024*2];
// The actual number of valid bytes received
Int r = socketSend. Receive (buffer );
// Converts the buffer into a readable string.
String str = Encoding. UTF8.GetString (buffer, 0, r );
ShowMsg (socketSend. RemoteEndPoint. ToString () + ":" + str );
}
}
SocketSend reading is incorrect. You also need to pass parameters of the same object type.
12. Return the while loop of Listen.
Enable a new thread to continuously receive messages sent from the client.
Thread th = new Thread (Recive );
Th. IsBackground = true;
Th. Start (socketSend );
Problem 1. Now I want to send a character for another line but display it in one line (this is normal as long as I use my own client to do it, skip it)
Problem 2. After the client is disabled, the server is still sending messages.
Because the client is closed, the actual information of r is null (that is, 0), but it is still being sent, so make a judgment
If (r = 0)
{Break ;}
Try-catch all areas that are prone to exceptions. NO content is written in catch.
13. Create a client Module
TxtServer (192.168.1.42) txtPort (50000) btnStart (connection)
TxtLog
TxtMsg
14. Click connection to enter btnSatrt_Click
Create the socket interNetwork responsible for communication, which indicates the IPV4 sockettype (type) stream protocoltype (service) Tcp
Socket socketSend = new Socket (AddressFamily. InterNetwork, SocketType. Stream, ProtocolType. Tcp );
The client is going to connect to the server
First, create the IP address of ipAddress in a static way.
IPAddress ip = IPAddress. Parse (txtServer. Text );
Then splice the IP address and port number together.
IPEndPoint point = new IPEndPoint (ip, Convert. ToInt32 (txtPort. Text ));
Obtain the IP address and port number of the server to be remotely connected.
SocketSend. Connect (point );
15. Create a method ShowMsg ()
Void ShowMsg (string str)
{
AppendText of the append text will not be overwritten.
TxtLog. AppendText (str + "\ r \ n ");
}
In step 14, a "connection succeeded" is passed in, indicating that the client is connected to the server.
ShowMsg ("connection successful ");
16. Connect to the server client and send messages to the server
You need to send txtMsg content to the server.
In the message sending event, enter btnSend_Click
Use socketSend for communication. But it cannot be written in another event, so I declare it outside.
SocketSend. send () sends messages to the server, which needs to be put into a byte array
The information in txtMsg. text that we want to send is received in string str, trim is to remove Spaces
String str = txtMsg. Text. Trim ();
Convert str to a byte array.
Byte [] buffer = Encoding. UTF8.GetBytes (str );
Send information to the server
SocketSend. Send (buffer );
17. The server sends messages to the client.
Written in the message sending event btnSend_Click
First declare Step 1 socket socketSend to the outside
Upload the txtMsg data to the client in step 1.
String str = txtMsg. Text ();
Byte [] buffer = Encoding. UTF8.GetBytes (str );
SocketSend. Send (buffer );
18. The client sends messages more than once, and keeps sending messages.
Write a Recive method that is the same as that of the server. Use wile (true) for loop usage
Void Recive ()
{
While (true)
{
}
}
Use socketSend. Receive to Receive the buffer of the byte array and return a valid number of bytes actually accepted r
Byte [] buffer = new byte [1024*1024*3];
Int r = socketSend. Receive (buffer );
For example, if (r = 0)
If (r = 0)
{
Break;
}
Decodes the array of information into string s for receiving.
String str = Encoding. UTF8.GetString (buffer, 0, r );
Call the ShowMsg method to connect the IP address and port number with the received information and output a line break, which is displayed on txtMsg.
RemoteEndPoint
ShowMsg (socketSend. RemoteEndPoint. ToString () + ":" + s );
19. Return the btnStart_Click event
To prevent the running of a single thread from getting stuck, you need to start a new thread and pass the Recive method into it to continuously accept messages sent from the server.
Thread th = new Thread (Recive );
Set as background thread
Th. IsBackground = true;
Th. Start ();
20. To prevent cross-thread errors
Disable cross-Thread Check during formateload Loading
Control. checkforillegalcrossthreadcils = false;
Try-catch for all network connections
21. Now, you can only communicate with the last connected client. Because the new client is connected, the original client is gone.
Therefore, the server needs a drop-down box to store remote IP addresses and ports and send messages to the specified client.
Use a key-value pair to store the Directory. Find the socketSend key-Value Pair Based on the string type IP address.
Dictionary <string, Socket> dicSocket = new Dictionary <string, Socket> ();
22. Add a set under socketSend of Listen.
Store the IP address and Socket of the remotely connected client into the collection.
Therefore, you cannot directly use socketSend to send a message. It is sent based on the selected IP address.
DicSocket. d (socketSend. RemoteEndPoint. ToString (), socketSend );
Store the IP address and port number of the remote connection to the cboUsers drop-down list.
CboUsers. Items. Add (socketSend. RemoteEndPoint. ToString ());
Go to btnSend_Click IP address and port
Obtain the ip address specified by the user in the drop-down list to the string type.
String ip = cboUsers. SelectedItem. ToString ();
DicSocket [ip]. Send (buffer );
Test
23. Now, the server and client can send and receive data from each other, but only for text data.
What is the distribution of files and vibrating clients on the server. Because the byte array is sent
Tell the client what is sent
Create a pseudo Protocol
Agreement is mutual agreement.
Operate on Byte Arrays
Mark to add the first byte of data according to the type, [0] indicates 0, text 1, file 3, vibration
24. Determine the server's receipt
Determine the receipt of the server
If the value is 0, it is processed by text, 1 by file, 2 by vibration.
The service end sends a message to the client btnSend_Click
Insert a byte [0] = 0 in the buffer;
The array length is unchangeable. You need to create an array to accept it and send it to the past.
Array length buffer. length + 1 buffer [0] = 0;
Assign a value to a new buffer and add it using a List generic set, and then convert it to a byte array.
List <byte> list = new List <byte> ();
List. Add (0 );
List. AddRange (list );
Byte [] newByte = list. ToArray ();
Finally, change the passed array to dicSocket [ip]. Send (newBuffer );
You cannot assign a value directly to the buffer because the length is different.
25. Return the message Recive sent from the client receiving server
Add the first number (0, 1, 2) to determine the actual data size after receiving the string)
If (buffer [0] = 0)
{
}
Put the processing code of the obtained text into this judgment.
Then expand other
Else if (buffer = 1)
{
}
Else if (buffer = 2)
{
}
If (r = 0) judgment can be put out, no need to write three
If (r = 0)
{
Break;
}
If the code for processing text is directly inserted, it will be problematic because the first number is added to the byte, which must be included.
The decoding starts from the second element (subscript: 1), because the first element is a tag class and is useless.
The number of decoded R-1. Because the first one is useless.
String s = Encoding. UTF8.GetString (buffer, 1, r + 1 );
Text will not be lost during testing
26. Select files on the server
When you click Select, the dialog box should pop up. Select the file to be sent from the btnSelect event.
OpenFileDialog ofd = new OpenFileDialog ();
Ofd. Title = "select the file to be sent ";
Ofd. InitialDirectory = @ "C: \ Users \ SJD \ Desktop ";
Ofd. Filter = "all files | *.*";
Ofd. ShowDialog ();
TxtPath. Text = ofd. FileName;
27. The server sends a file
Click Send File btnSend
Obtain the path of the file to be sent
String path = txtPath. Text;
Read data streams
Using (FileStream fsRead = new FileStream (path, FileMode. Open, FileAccess. Read ))
{
Byte [] buffer = new byte [1024*1024*5];
Int r = fsRead. Read (buffer, 0, buffer. Length );
Get the socket responsible for communication and send the byte array buffer.
Set the buffer size so that it can be sent as the actual parameter size.
Buffer array, from 0 to r, with no enumerated Parameters
DicSocket [cboUsers. SelectedItem. ToString ()]. Send (buffer, 0, r, SocketFlags. None );
}
You need to add the value 1 to the first byte, so
Using (FileStream fsRead = new FileStream (path, FileMode. OpenOrCreate, FileAccess. Read ))
{
Byte [] buffer = new byte [1024*1024*5];
Int r = fsRead. Read (buffer, 0, buffer. Length );
// Set the buffer size so that it can be sent as the actual parameter size.
List <byte> list = new List <byte> ();
List. Add (1 );
List. AddRange (buffer );
Byte [] newBuffer = list. ToArray ();
DicSocket [cboUsers. SelectedItem. ToString ()]. Send (newBuffer, 0, r + 1, SocketFlags. None );
}
28. Find the client to start receiving
Create the saveFileDialog object in else if (buffer [0] = 1)
SaveFileDialog sfd = new SaveFileDialog ();
Sfd. Title = "select the file to save ";
Sfd. InitialDirectory = @ "C: \ Users \ SJD \ Desktop ";
Sfd. Filter = "all files | *.*";
Add this to win8. Otherwise, the saved directory cannot pop up.
Sfd. ShowDialog (this );
String path = sfd. FileName;
Using (FileStream fsWrite = new FileStream (path, FileMode. OpenOrCreate, FileAccess. Write ))
{
FsWrite. Write (buffer, 1, r-1 );
MessageBox. Show ("saved successfully ");
}
Try-catch whenever there is a problem.
29. Send a vibrate message to the btnZD_Click event
Create a byte array, put it in 2, and send it to the specified IP Client based on its key-value pairs.
Byte [] buffer = new byte [1];
Buffer [0] = 2;
DicSocket [cboUsers. SelectedIte () m. ToString ()]. Send (buffer );
30. Set the client to vibrate
How to Create a vibration on the client
Void ZD ()
{
The form (client) has been continuously assigned a value for 500 cycles, and the position has been moved.
For (int I = 0; I <500; I ++)
{
This. Location = new Point (200,200 );
This. Location = new Point (230,230 );
}
Go to else if (buffer [0] = 2) and put the ZD () method in.