Java-socket Communication Basics

Source: Internet
Author: User
Tags connect socket

Two modes of communication, TCP/UDP

TCP to have a server-side socket, ServerSocket, the client can connect with the socket, and then communicate with each other according to the protocol. No open/start. But close.

Communication is Socket.getinputstream () Socket.getoutputstream () with buffer packaging is better, output remember refresh

UDP server side with Datagramsocket (listening port), create Datagrampacket to receive data

The UDP client is constructed with the Datagramsocket null parameter, creating Datagrampacket (data, data.length, address, Port), placing the address, length, destination IP, and port

Below is an example:

Import Java.io.ioexception;import Java.net.datagrampacket;import Java.net.datagramsocket;import java.net.inetaddress;/* * Server-side, implementation of UDP-based user login */public class Udpserver {public static void main (string[] args) throws Ioexce ption {/* * receives the data sent by the client *///1. Create a server-side datagramsocket, specify the port datagramsocket socket=new datagramsocket (8800),//2. Create a datagram, Used to receive data sent by the client byte[] data =new byte[1024];//Create byte array, specify the size of the received packet Datagrampacket packet=new datagrampacket (data, Data.length)//3. Receive the data sent by the client System.out.println ("The server side has been started, waiting for the client to send data"); socket.receive (packet);// This method will block//4 until the datagram is received. Read Data string Info=new string (data, 0, packet.getlength ()); System.out.println ("I am the server, the client says:" +info);/* * Respond to the client data *///1. Defines the client's address, port number, data inetaddress address=packet.getaddress (); int Port=packet.getport (); byte[] data2= "Welcome!". GetBytes ();//2. Create a datagram that contains the data information for the response Datagrampacket packet2=new datagrampacket (data2, Data2.length, address, port);//3. Response Client Socket.send (Packet2);//4. Close Resource Socket.close ();}} Import Java.io.ioexception;import java.net.datagrampacket;import jaVa.net.datagramsocket;import Java.net.inetaddress;import Java.net.socketexception;import  java.net.unknownhostexception;/* * Client */public class UdpClient {public static void main (string[] args) throws IOException {/* * Send data *///1 to server side. Define the server's address, port number, data inetaddress address=inetaddress.getbyname ("localhost"); int port=8800;byte[] Data= "username: admin; password: 123". GetBytes ()//2. Create a datagram that contains the data that is sent Datagrampacket packet=new datagrampacket (data, Data.length, address, port);//3. Create Datagramsocket Object Datagramsocket socket=new datagramsocket ();//4. Sending datagrams to the server Socket.send (packet) ;/* * Receive server-side response data *///1. Create datagrams for receiving server-side response data byte[] data2=new byte[1024];D atagrampacket packet2=new datagrampacket ( Data2, Data2.length)//2. The Data socket.receive (Packet2) of the receiving server response;//3. Read Data string Reply=new string (data2, 0, Packet2.getlength ()); System.out.println ("I am the client, server says:" +reply);//4. Close Resource Socket.close ();}} Import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.inputstream;import Java.io.inputstreamreader;import Java.io.outputstream;impORT java.io.printwriter;import java.net.socket;import java.net.unknownhostexception;/* * Client */public class Client { public static void Main (string[] args) {try {//1. Create client socket, specify server address and port socket socket=new socket ("localhost", 8888);//2. Get the output stream, send information to server side OutputStream Os=socket.getoutputstream ();//byte output stream printwriter pw=new printwriter (OS);// Wraps the output stream as a print stream pw.write ("User name: Alice; Password: 789");p W.flush (); Socket.shutdownoutput ();//close output stream//3. Get the input stream, and read the server-side response information InputStream is=socket.getinputstream (); BufferedReader br=new BufferedReader (New InputStreamReader (IS)); String Info=null;while ((Info=br.readline ())!=null) {System.out.println ("I am the client, the server says:" +info);} 4. Closing resources br.close (); Is.close ();p w.close (); Os.close (); Socket.close ();} catch (Unknownhostexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ()}}} Import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.inputstream;import Java.io.inputstreamreader;import Java.io.outputstream;import Java.io.printwriter;import java.net.InetAddress; Import Java.net.serversocket;import java.net.socket;/* * Socket communication based on TCP protocol, implementation of user login * Server-side */public Class Server {public St atic void Main (string[] args) {try {//1. Create a server-side socket, that is, ServerSocket, specify the bound port, and listen for this port ServerSocket serversocket=new ServerSocket (8888); Socket socket=null;//Record the number of clients int count=0; SYSTEM.OUT.PRINTLN ("* * * server is about to start, waiting for client Connection");//loop listener waits for the client to connect while (TRUE) {//calls the Accept () method to start listening, waiting for the client to connect socket= Serversocket.accept ();//Create a new thread Serverthread serverthread=new serverthread (socket);//Start thread serverthread.start (); The number of count++;//statistics clients System.out.println ("Number of clients:" +count); inetaddress address=socket.getinetaddress (); System.out.println ("IP of the current client:" +address.gethostaddress ());}} catch (IOException e) {e.printstacktrace ();}}} Import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.inputstream;import Java.io.inputstreamreader;import java.io.outputstream;import Java.io.printwriter;import java.net.Socket;/* * Server threading Classes */public class Serverthread extends Thread {//and Socketsocket socket associated with this thread = NuLl;public Serverthread (socket socket) {this.socket = socket;} A thread performs an operation that responds to the client's request public void run () {InputStream is=null;inputstreamreader isr=null; BufferedReader Br=null;outputstream Os=null; PrintWriter pw=null;try {//Gets the input stream and reads the client information is = Socket.getinputstream (); ISR = new InputStreamReader (is); br = new BufferedReader (ISR); String Info=null;while ((Info=br.readline ())!=null) {//iterates over the client's information System.out.println ("I am the server, the client says" +info);} Socket.shutdowninput ();//Close input stream//Get output stream, respond to client request OS = Socket.getoutputstream ();p w = new PrintWriter (OS);p w.write ("Welcome! ");p W.flush ();//Call Flush () method to buffer output} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();} finally{//Close Resource try {if (pw!=null) pw.close (); if (os!=null) os.close (); if (br!=null) br.close (); if (isr!=null) Isr.close ( ); if (is!=null) is.close (); if (socket!=null) Socket.close ();} catch (IOException e) {e.printstacktrace ();}}}}


Java-socket Communication Basics

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.