Client/sever Mode of communication--java

Source: Internet
Author: User
Tags date1

c/S communication based on UDP mode This is the client side:
Import Java.net.*;import java.io.*;p ublic class udpclient{public static void Main (String args[]) {Datagramsocket socket = Null;datagrampacket packet = null;inetaddress address = null; String s = "Send the data, please!"; byte buf[] = new Byte[256];buf = S.getbytes (); byte ip[] = {(byte) 127, (byte) 0, (byte) 0, (byte) 1};try{address = INETADDRESS.G Etbyaddress (IP), socket = new Datagramsocket ();p acket = new Datagrampacket (buf,buf.length,address,1080); Socket.send ( packet); Thread.Sleep (+);p acket = new Datagrampacket (buf,buf.length); socket.receive (packet); s = new String (Packet.getdata ( )); System.out.println ("Received data is:" +s); catch (Exception e) {System.out.println (e.tostring ());} Socket.close ();}}

This is the sever side:
Import java.net.*;import java.io.*;import java.util.*;p ublic class udpsever{public static void Main (String args[]) { Datagramsocket Socket1=null;datagrampacket Packet1=null; String s1;byte buf1[]= new byte[256];inetaddress Address1 = null;int port1;date date1;try{socket1 = new Datagramsocket (108 0);p Acket1 = new Datagrampacket (buf1,buf1.length); socket1.receive (PACKET1); S1=new String (Packet1.getdata ()); System.out.println ("Received request:" +s1);p Ort1 = Packet1.getport (); address1= packet1.getaddress ();d ate1 = new Date ( ); s1 = date1.tostring (); buf1= s1.getbytes ();p acket1= new Datagrampacket (BUF1,BUF1.LENGTH,ADDRESS1,PORT1); Socket1.send (PACKET1); Thread.Sleep (2000);} catch (Exception e) {System.out.println (e.tostring ());} Socket1.close ();}}


If you change this IP address. You can do simple network communication. Network programming just contact, slowly learn.

Client/sever Mode of communication--java

Related Article

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.