Source code for socket programming in java

Source: Internet
Author: User

Socke, also known as "socket", is used to describe IP addresses and ports. It is a communication chain handle. Applications usually send requests to or respond to network requests through "Sockets.

Compile the socke server code:

Package com. evan. blog; import java. io. IOException; import java. io. inputStream; import java.net. serverSocket; import java.net. socket; public class BlogServer {public static void main (String [] args) {try {ServerSocket serverSocket = new ServerSocket (8080); Socket socket = serverSocket. accept (); InputStream is = socket. getInputStream (); byte [] B = new byte [1024]; int len; StringBuffer sb = new StringBuffer (); wh Ile (len = is. read (B ))! =-1) {String str = new String (B, 0, len); sb. append (str);} is. close (); System. out. println (sb. toString (); System. out. println ("Someone has accessed port 8080 of the Local Machine and passed in '" + sb. toString () + "'value");} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();}}}
Client source code:

Package com. evan. blog; import java. io. IOException; import java. io. outputStream; import java.net. inetAddress; import java.net. socket; import java.net. unknownHostException; public class BlogClient {public static void main (String [] args) {try {Socket socket = new Socket (InetAddress. getLocalHost (). getHostAddress (), 8080); // obtain the local IP address OutputStream OS = socket. getOutputStream (); String str = "my blog socket"; OS. write (str. getBytes (); OS. flush (); OS. close ();} catch (UnknownHostException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();}}}


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.