Java TCP/IP synchronous message transmission

Source: Internet
Author: User

Tcpserver. Java:

Import java.net. *; // packages used for TCP/IP socket programming
Import java. Io .*;

Public class tcpserver {
Public static void main (string [] ARGs) throws exception {
Serversocket Ss = new serversocket (6666); // apply for a new sever port. Generally, over 1024 is used, because it may be called by the system at any time.
While (true ){
Socket S = ss. Accept (); // The socket accepts the information. It is blocked. If not, it will wait.
// Asynchronous Method. Otherwise, it will waste time.
System. Out. println ("A Client Connected! ");
Inputstream is = S. getinputstream (); // receives the message
Datainputstream Dis = new datainputstream (is );
System. Out. println (DIS. readutf (); // print the message sent from the client. Of course, readutf is also blocked and waits until it does not exist.
// Readutf is blocking ..
Dis. Close (); // close the data input stream
S. Close (); // close the current port ..
}
}
}

Tcpcllient. Java:

Import java.net .*;
Import java. Io .*;

Public class tcpclient {
Public static void main (string [] ARGs) throws exception {
Socket S = new socket ("127.0.0.1", 6666 );
// Socket (string host, int port); server IP address, and corresponding port number.Program..

// Data source. Data is sent from the outputstream on the port.
Outputstream OS = S. getoutputstream ();
// Thread. Sleep (30000); // for testing, readutf is blocking.
Dataoutputstream dos = new dataoutputstream (OS );
Dos. writeutf ("Hello server! ");
Dos. Flush ();
Dos. Close ();
S. Close ();
}
}

 

Java has provided asynchronous TCP/IP programming. This is synchronous. Simple basic communication... for reference.

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.