UDP broadcast and TCP client--server

Source: Internet
Author: User

With the countdown to the noise, consciously inadvertently work, just want to celebrate the motherland.

Recently encountered such a problem, the camera identified by the pedestrian, the vehicle in real-time display in the client. There is an interface that will post the recognized object in real time in the form of JSON data. So we're going to write a Web service that continues to receive data and then parse the data into the database. Up to this point, the data is not a problem, all in the database, so there is a real-time refresh to identify the picture problem. Before the processing method is every 5 seconds or so to read the latest database news, with a timer timer to solve, so that can solve the problem, but the feeling is not the best way, because the camera recognition of the object is time-sensitive, such as the midnight almost no one through, This time back in the background is still to get the latest data to judge the consumption of resources. So I first think of the TCP method to deal with, the web in the resolution of the picture, send, WinForm the client to receive. Seems to solve the problem, first on the code

        Private voidButton1_Click (Objectsender, EventArgs e) {            //Create a TCP client objectTcpClient TcpClient =NewTcpClient (); //Add the IP, port number of the destination (server) hostTcpclient.connect (Ipaddress.parse ("172.16.0.217"),8056); //the form of network stream dataNetworkStream NetworkStream =Tcpclient.getstream (); if(networkstream.canwrite) {//pending data transfer byte[]byte[] Bytsend =Encoding.UTF8.GetBytes (TextBox1.Text); Networkstream.write (Bytsend,0, bytsend.length); }            Else{MessageBox.Show ("unable to write to the data stream");                Networkstream.close ();                Tcpclient.close (); return; }            //when the stream is created, it needs to closeNetworkstream.close ();        Tcpclient.close (); }  

This is the client of TCP, which specifies the IP and port number of the receiving end, and the data stream to be sent, and also chooses to accept the stream data on the server. Server to continue to receive data , you must open a thread to listen

        Private voidForm1_Load (Objectsender, EventArgs e) {            //Initializing Load DataThread thread =NewThread (NewThreadStart (Listen)); Thread.        Start (); }        //adding strings and delegates to text box TXTRECVMSSG in a thread        Private Delegate voidServerrecdeg (strings); Private voidReceivemsg (stringmes) {TextBox1.Text="Time :"+ DateTime.Now.ToLongTimeString () +"Data:"+mes; }        //Listening Data        Private voidListen () {//Socket ObjectSocket sock =NewSocket (Addressfamily.internetwork,sockettype.stream, protocoltype.tcp); Sock. Bind (NewIPEndPoint (Ipaddress.any, 8056)); //constantly listening to ports             while(true) {sock. Listen (0); Socket Socket=sock.                Accept (); NetworkStream Ntwstream=NewNetworkStream (socket); StreamReader Strmreader=NewStreamReader (Ntwstream); //WinForm UI Control is assigned value, if the thread, you need to use Invoke to assign a value, then no errorInvoke (NewServerrecdeg (receivemsg),New Object[] {strmreader.readtoend ()}); Socket.            Close (); }                    }

Above is the TCP client sends the data, the service side receives continuously. I thought it was okay at first, but then it was really not feasible. I am the Web server is sending data, the client is used to receive data. TCP is the client to specify the server-side unique IP and port number for data transmission, there is obviously a conflict, if the Web server to send data with TCP,

There can only be one client to receive, the demand is WinForm finally to deploy to different machines, this kind of thinking certainly not. Reasoning, finally in the colleague's guidance, thought of the broadcast of this idea. In the Web server each time the resolution to the picture, send a broadcast, and then hidden in the LAN of the various clients can listen to, after parsing the picture

        //Defining Objects        Private StaticSocket sock; Private StaticIPEndPoint IPEndPoint; Private Static byte[] data; //Send broadcast         Public Static voidUdpsend (byte[] bytes1) {            //sock object, specifying the UDP protocolSock =Newsockets (AddressFamily.InterNetwork, Sockettype.dgram, PROTOCOLTYPE.UDP); IPEndPoint=NewIPEndPoint (Ipaddress.broadcast,9050); //Assign Valuedata =bytes1; Sock. SetSocketOption (Socketoptionlevel.socket, Socketoptionname.broadcast,1); //Sendsock.        SendTo (data, IPEndPoint); }

Here is the use of UDP broadcast, the code is very small, the sending side has been completed, the rest is the client continues to receive the broadcast

         Public voidReceive () {Try            {                //Scok object, setting UDP protocolSocket sock =Newsockets (AddressFamily.InterNetwork, Sockettype.dgram, PROTOCOLTYPE.UDP); //Timeout periodSock. ReceiveTimeout =4000; //the broadcast port number specifiesIPEndPoint IEP =NewIPEndPoint (Ipaddress.any,9050); Sock.                Bind (IEP); EndPoint EP=(EndPoint) IEP; //Data Reception (specifies the method to receive asynchronously)Sock. BeginReceive (Buffer,0, buffer. Length, Socketflags.none,NewAsyncCallback (ReceiveMessage), sock); }            Catch(Exception ex) {MessageBox.Show (ex).            Message); }        }        //the size of the image stream buffer that the order receives        Static byte[] buffer =New byte[102400]; //Asynchronous Receive         Public voidReceiveMessage (IAsyncResult ar) {Try            {                varSocket = ar. AsyncState asSocket; varLength =socket.                EndReceive (AR); //read out the message content//var message = Encoding.UTF8.GetString (buffer, 0, length); //first three lengths for object type vehicle/pedestrian, rear identification image//Parse Picture type                stringObjType = System.Text.Encoding.Default.GetString (buffer. Skip (0). Take (3).                ToArray ()); //Parse PictureImage img = convertimg (buffer. Skip (3).                                              ToArray ()); //displaying Messages                 This. Invoke (NewAction (() ={setpicboximg (ObjType, IMG);}); //receive the next message (recursive)Socket. BeginReceive (Buffer,0, buffer. Length, Socketflags.none,NewAsyncCallback (ReceiveMessage), socket); }            Catch(Exception ex) {MessageBox.Show (ex).            Message); }        }

When this is done, the rest is to write the method of receiving the broadcast to the background thread, which can be started when the form is running.

New Thread (newtrue; TD. Start ();

Well, things are basically over here, you can see that the code is very small, but can solve the needs of real-time refresh. After encountering things must be clear thinking, or a start to get into the TCP cul-de-sac, how can not come out, wasted time not to say, people also made very tired. Here thanks to the guidance of colleagues, after much like technical master learning, after all, experience is sometimes really hard power.

UDP broadcast and TCP client--server

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.