Java Socket Communication Client server-side base code

Source: Internet
Author: User

"Server-side"

Import Java.io.ioexception;import java.io.inputstream;import Java.net.serversocket;import java.net.Socket;public Class TestServer {public static void main (string[] args) {try {System.out.println ("Start service side"); ServerSocket SV = new ServerSocket (2233);//waits for user to link socket socket = sv.accept (); SYSTEM.OUT.PRINTLN ("There are user links! "); while (true) {//1inputstream is = Socket.getinputstream ();//2byte[] data = new Byte[128];is.read (data,0,data.length) The//3 is converted to a string by the format output string msg = new String (data, "UTF-8");//received Content System.out.println ("Received:" + msg);}} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}

"Client Side"

Import Java.io.ioexception;import java.io.outputstream;import Java.net.socket;import java.net.UnknownHostException Import Java.util.scanner;public class TestClient {public static void main (string[] args) {try {socket socket = new socket ("192.169.191.4", 2244);//socket socket = new Socket ("localhost", 2233); SYSTEM.OUT.PRINTLN ("Link Server succeeded! "); while (true) {System.out.println (" Please enter content: ");//1scanner input = new Scanner (system.in); String msg = Input.next ();//2outputstream os = Socket.getoutputstream ();//3byte[] data = msg.getbytes ("UTF-8"); os.write (data); Os.flush ();}} catch (Unknownhostexception e) {//Todo auto-generated catch Blocke.printstacktrace ()} catch (IOException e) {//Todo Aut O-generated catch Blocke.printstacktrace ();}}}


Java Socket Communication Client server-side base code

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.