[Optical camera] network communication methods and functions, optical camera network communication
1. TcpClient and TcpServe.
First, we need to know the IP address of the server and establish a listener on the server. After listening to the connection request from the client, we need to connect to the client.
The client needs to connect to the specified IP server address and establish a network stream to implement communication.
Next we will provide an instance for the server and client:
Server:
Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; using System. net; using System. net. sockets; namespace fuwuqi {class Program {static void Main (string [] args) {try {IPAddress Ip = IPAddress. parse ("127.0.0.1"); // IPAddress provides the Internet Protocol Address class. Parse converts the Ip address string to the IPAddress instance TcpListener TcpList = new TcpListener (Ip, 8888 ); // TcpListener network listener class, which detects Listen to the connection, TcpListener (parameter 1, parameter 2), parameter 1 indicates the local IP address, and parameter 2 indicates to listen to the incoming port connection TcpList. start (); // Start the listener Console for the incoming connection request to suspend connections. writeLine ("Server start! "); Console. writeLine ("Ip address:" + TcpList. localEndpoint); // LocalEndpoint obtains information such as the server (local) address and port. writeLine ("Wait"); Socket Soc = TcpList. acceptSocket (); // after the client is started, the Socket is suspended. // AcceptSocket indicates that the client accepts the suspended connection request. The Socket is the Console of the Socket interface. writeLine ("Received Connection:" + Soc. remoteEndPoint); // RemoteEndPoint obtains information such as the client address and port. byte [] B = new byte [100]; int k = Soc. receive (B); // Soc. receive (B) receives data from the socket and saves the data to the receiving slow In the punch area list, the value of k is the Data Length Console. writeLine ("Received data from client:"); for (int I = 0; I <k; I ++) Console. write (Convert. toChar (B [I]); // Convert. toChar (B [I]) converts array B to char and outputs ASCIIEncoding AS = new ASCIIEncoding (); // ASCIIEncoding indicates the ASCII character encoding class Soc of Unicode characters. send (. getBytes ("Received data! "); // Soc. send sends data to the client,. getBytes () obtains the bytes value Soc of the string in parentheses. close (); // Close the connection and release all associated resources TcpList. stop (); // close the listener Console. readLine (); // wait for the input to pause} catch (Exception e) {Console. writeLine ("Error! "+ E. StackTrace); // gets the string of frames on the call stack when the current exception occurs }}}}
At this time, the server applies the Socket class to send data streams. The Socket class is used by both the client and the server. Its sending mechanism is sent in the form of a package. During project creation, it is found that the data packet received by the Socket is not necessarily consistent with the length of the sent data packet and is blocked. Therefore, when using the Socket data packet to send, the length of the data group to receive and send must be specified, too long will also lose the number.
Client:
Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; using System. IO; using System. net. sockets; namespace kehuduan {class Program {static void Main (string [] args) {try {TcpClient = new TcpClient (); // TcpClient is a class TcpClient that provides client connection for TCP network services. connect ("127.0.0.1", 8888); // Connect the client to the remote TCP host Console using the specified IP address and port number. writeLine ("Connect C Omplete "); Console. writeLine ("Input string:"); String str = Console. readLine (); // defines the str variable of the string and stores the input character Stream stm = TcpClient. getStream (); // defines the data stream, used to send and receive data ASCIIEncoding AS = new ASCIIEncoding (); byte [] B =. getBytes (str); // converts a string to a byte type stm. write (B, 0, B. length); // Write (parameter 1, parameter 2, parameter 3) indicates to send a string to the server, and parameter 1 indicates to copy the array to the current stream, parameter 2 refers to the byte offset starting from scratch, and parameter 3 refers to the number of bytes to be written to the current stream (that is, the string length) Console. writeLine ("Send Complete"); byte [] bb = New byte [100]; int k = stm. read (bb, 0,100); // stm. read reads the response information sent from the server in the current stream. Its parameters are consistent with the Write method parameters. The k value is the length of the Read string for (int I = 0; I <k; I ++) Console. write (Convert. toChar (bb [I]); TcpClient. close (); // release the TcpClient instance and do not Close the basic connection Console. readLine ();} catch (Exception e) {Console. writeLine ("Error! "+ E. StackTrace );}}}}
The preceding figure shows the simple communication between the client and the server. As an example program, we will record the connection to the camera server in our own project.
First, take the camera as the server side and define the client:
TcpClient client = new TcpClient ("IP", 8080 );
Get network stream:
NetworkStream networkstream = client. GetStream (); // gets the network stream
In this case, you can establish a network stream connection with the server. If you need to read or write data from the network stream, you can use BinaryReader/BinaryWriter or StreamReader/StreamWriter. after instantiation, You can implement stream read/write.
BinaryReaderbr = new BinaryReader (networkstream );
BinaryWriter bw = new BinaryWriter (networkstream );
My understanding of the two is that StreamReder reads functions such as ReadToEnd and ReadLine and reads them as strings. BinaryReader can read data by byte. Select as needed.
(Method of recording StreamReader: sr. BaseStream. Seek (0, SeekOrigin. Begin); // the offset of the current start position (SeekOrigin. begin) of the stream to 0)
If you need to directly Write data to the server, you can use functions such as Write.
Here we will also summarize the materials we have found.
MemoryStream class:
The Memmory class is equivalent to a cache stream. First, you need to open up a space for the stream and then put the data into the stream for operations. The advantage of this stream is that the data can be first put into the stream, and then any byte in the pointer stream can be used for operations.
Learning example:
Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; using System. IO; namespace ConsoleApplication1 {class Program {static void Main (string [] args) {// property test MemoryStream MS = new MemoryStream (); Console. writeLine (ms. canRead); // True memory stream readable Console. writeLine (ms. canSeek); // True the memory stream supports searching, and the pointer is moved to the searching Console. writeLine (ms. canTimeout); // False memory stream not supported Timeout Console. writeLine (ms. canWrite); // True memory stream can be written to the Console. writeLine (ms. capacity); // The number of bytes allocated to the stream by 0. byte [] bytes = Encoding. UTF8.GetBytes ("abcdedcba"); // convert the character to ASCII ms. write (bytes, 0, bytes. length); // you have written a piece of text to the memory int l = bytes. length; Console. writeLine (ms. capacity); // 256 the number of bytes allocated for the text stream to be read again has changed to 256. It seems that the memory stream is allocated to the Console Based on the quantity required. writeLine (ms. length); // 9 This is the stream Length, which is usually the same as the number of English characters and actually occupies the number of bytes. Console. writeLine (ms. position); // 9 the current Position of the stream. This attribute can be set to readable. // Console. writeLine (ms. readTimeout); because the Stream does not support timeout, if this attribute is read or set, an error will be reported // Console. writeLine (ms. writeTimeout); because the Stream does not support timeout, if this attribute is read or set, an error is returned // method test byte [] byte1 = ms. getBuffer (); // The returned unsigned byte array is almost fooled. The unsigned byte array is actually byte (0 ~ 255), signed byte sbyte (-128 ~ 127) string str1 = Encoding. UTF8.GetString (byte1); Console. writeLine (str1); // output abcdedcba long p = ms. position; // the current Position of the pointer in ms. position = 0; ms. seek (0, SeekOrigin. current); // set the starting position of the Current stream to start from 0 // read a byte int I = ms from the memory. readByte (); Console. writeLine (I); // output 99 byte [] bytes3 = ms. toArray (); foreach (byte B in bytes3) {Console. write (B + "-"); // compare the output 97-98-99-100-101-100-99-98-97-you can see that 0, 1, 2, the second digit is 9. 9} MemoryStream ms2 = new MemoryStream (); byte [] bytes6 = Encoding. UTF8.GetBytes ("abcde"); ms2.Write (bytes6, 0, bytes6.Length); Console. writeLine (ms2.Position); // After the output is finished, the stream position ends. Therefore, the following line of code must be added to read data with read. // Ms2.Seek (0, SeekOrigin. Begin); // to Read the complete stream using the Read method, you must set the current Position. Read starts from the Position. Ms2.Position = 0; // Read is Read from the current position. This line of code has the same meaning as the previous line. Byte [] byteArray = new byte [5] {0, 0, 0, 0}; // The initial values of the array are all 0 ms2.Read (byteArray, 2, 1 ); // read one byte. In the first element of byteArray (note that it starts from 0), read the second position in the data stream and start reading a Console. writeLine (Encoding. UTF8.GetString (byteArray); // nnann ms2.Read (byteArray, 2, 2); Console. writeLine (Encoding. UTF8.GetString (byteArray); // when the total length of the received array is exceeded, the subsequent elements are removed // set the length of the current stream Console. writeLine (ms. length); // output 9 the Length of the current stream is 9 ms. setLength (20); Console. writeLine (ms. length); // output 20 foreach (byte B in ms. toArray () // converts the stream content, that is, the content in the memory, to a byte array {Console. write (B + "-"); // output 97-98-99-100-101-100-99-98-97-0-0-0-0-0-0-0-0-0-0-0 due to Settings length, so empty auto-fill 0} Console. writeLine (Encoding. UTF8.GetString (ms. toArray (); // although the length of the output abcdedcba is longer, it does not affect the read data MemoryStream ms1 = new MemoryStream (); byte [] bytes4 = ms1.ToArray (); Console. writeLine ("this memory stream does not Write data (Write)" + Encoding. UTF8.GetString (bytes4); // The output memory stream is not written into data (Write) because the memory is empty // Write to MemoryStream ms3 = new MemoryStream () at a specified position below (); byte [] bytesArr = Encoding. ASCII. getBytes ("abcdefg"); ms3.Write (bytesArr, 0, bytesArr. length); ms3.Position = 2; ms3.WriteByte (97); // 97 indicates that the Code a represents replacing the second c with a string str = Encoding. ASCII. getString (ms3.ToArray (); Console. writeLine (str); // output abacdefg byte [] byteArr1 = Encoding. ASCII. getBytes ("kk"); ms3.Position = 4; ms3.Write (byteArr1, 0, byteArr1.Length); Console. writeLine (Encoding. UTF8.GetString (ms3.ToArray (); // abadkkg // replace two bytes with the KK Console from the 4th-bit value. readKey ();}}}