Day20 Java Socket Usage

Source: Internet
Author: User

Use of sockets in Java


Client Side

Package Org.tizen.test;import Java.io.ioexception;import Java.io.outputstream;import java.net.inetaddress;import Java.net.socket;import Java.net.sockettimeoutexception;public class Testsocket {public static void main (String []str) { OutputStream OS = null; Socket socket = null;try {//1. The object that created the socket, indicating the IP address of the server by the constructor, and the port number received socket = new socket (Inetaddress.getbyname (" 192.168.1.104 "), 9000);//2.getoutputstream send data, return Outputstreamos = Socket.getoutputstream ()//3. Specific output process Os.write (" 1111111111  1111111111 ". GetBytes ());} catch (Exception e) {//Todo:handle exception}finally{//4. Close the specific stream and Socketif (os!=null) {try {os.close ();} catch ( IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}} if (socket!=null) {try {socket.close ()} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}}


Server Side


Package Org.tizen.test;import Java.io.ioexception;import Java.io.inputstream;import java.net.serversocket;import Java.net.socket;public class Testtcpip {public static void main (String []str) {ServerSocket SS = null; Socket s = null;inputstream is = null;try {//1. Creates a Socketserver object, indicating its own port SS = new ServerSocket (9000) via the constructor;//2. Calling sockets Erver The Accept method, returns a socket object s = ss.accept ();//3. Calling the getinputstream of the socket object gets the stream that the client sent over is = S.getinputstream (); byte[] B = new Byte[20];int len; while (len = Is.read (b))!=-1) {string str1 = new String (B,0,len); System.out.println (STR1);}} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Day20 Java Socket Usage

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.