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.