1. 簡單的 telnet echo server 原始碼:
// echo.java
import java.net.*;
import java.io.*;
class Echo extends Thread {
public static void main(String args[ ]) {
new Echo( ).start( );
}
public void run() {
try {
ServerSocket server = new ServerSocket(8080, 1); // listen for tcp port 8080
Socket client = server.accept(); // wait for client to connect
while (true) {
BufferedReader instream = new BufferedReader( new InputStreamReader(client.getInputStream( ) ) ) ; // input stream
BufferedWriter outstream = new BufferedWriter( new OutputStreamWriter(client.getOutputStream( ) ) ) ; // output stream
String text = instream.readLine()+"\n"; // read from input stream, add EOL and save to text
if( text.toLowerCase().equals( "quit\n") ) { // check the text
client.close(); // if true , close the socket
break;
}
outstream.write(text, 0, text.length() ); // write to output stream
outstream.flush(); // flush the output stream
}
} catch (IOException err) {
System.err.println(err);
}
}
}
2. 編譯
javac echo.java
3. 產生 Echo.class, 接著用 JVM 來執行執行:
java Echo
4. 開啟另一個終端機並使用 telnet 來連接, 輸入 quit 會結束程式並離開
telnet 127.0.0.1 8080
沒有留言:
張貼留言