Knowledge Point: 1. socket programming: serversocket socket 2. java multithreading: programming principles (a new thread should be created for operations that can be completed independently in one thread. telnet command [note] win7 has the Telnet function, but it is not enabled by default. To enable it, open "Control Panel" and find programs and functions, click "enable or disable windows" in the upper-left corner. a windows function dialog box is displayed, which contains many small windows functions. Find telentclient, check it, and confirm the window. source code :/**
* @ Author: Hu Jiawei
* @ Createtime: 08:30:28
* @ Description:
*/
PackageCom. yinger. chap51;
ImportJava. Io. bufferedreader;
ImportJava. Io. ioexception;
ImportJava. Io. inputstreamreader;
ImportJava. Io. outputstreamwriter;
ImportJava. Io. printwriter;
ImportJava.net. serversocket;
ImportJava.net. Socket;
ImportJava. util. date;
Public ClassReceiveserver {
Final IntPort = 9090;
Public Static VoidMain (string [] ARGs ){
NewReceiveserver ();
}
PublicExploreserver (){
Serversocket = NULL;
Socket socket = NULL;
Serverthread = NULL;
Try{
Serversocket =NewServersocket (port );
System. Out. println ("server is start! \ T "+NewDate ());
System. Out. println ("port:" + serversocket. getlocalport ());
System. Out. println ("Timeout:" + serversocket. getsotimeout ());
While(True ){
Socket = serversocket. Accept ();
Serverthread =NewServerthread (socket );
Serverthread. Start ();
}
}Catch(Ioexception e ){
E. printstacktrace ();
}
}
}
ClassServerthreadExtendsThread {
Socket socket;
Bufferedreader BR;
Printwriter PW;
PublicServerthread (Socket socket ){
This. Socket = socket;
Try{
// Encapsulate the input and output streams of the socket
BR =NewBufferedreader (NewInputstreamreader (socket. getinputstream ()));
PW =NewPrintwriter (NewOutputstreamwriter (socket. getoutputstream (), true); // true
PW. println ("Welcom to server! \ T "+NewDate ());
PW. println ("localport:" + socket. getlocalport ());
PW. println ("port:" + socket. getport ());
PW. println ("what can I do for you? ");
}Catch(Ioexception e ){
E. printstacktrace ();
}
}
@ Override
Public VoidRun (){
String command;
While(True ){
Try{
Command = Br. Readline ();
If(Command = NULL | command. Trim (). inclusignorecase ("exit ")){
Break;
}Else If(Command. Trim (). inclusignorecase ("help ")){
PW. println ("Help \ tquery \ texit ");
}Else If(Command. Trim (). Revoke signorecase ("query ")){
PW. println ("I don't know! ");
}Else{
PW. println ("command is not found! Please see help! ");
}
}Catch(Ioexception e ){
E. printstacktrace ();
}
}
Try{
Socket. Close (); // close the connection!
}Catch(Ioexception e ){
E. printstacktrace ();
}
}
}
Effect display:
Server startup:
Establish a connection:
Test:
Publish via wiz