服務器端:
//: JabberServer.java
// Very simple server that just
// echoes whatever the client sends.
package foo;
import java.io.*;
import java.net.*;
public class Server {
// Choose a port outside of the range 1-1024:
public static final int PORT = 8080;
public static void main(String[] args) throws IOException {
ServerSocket s = new ServerSocket(PORT);
System.out.println("Started: " + s);
try {
// Blocks until a connection occurs:
Socket socket = s.accept();
try {
System.out.println("Connection accepted: " + socket);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// Output is automatically flushed
// by PrintWriter:
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),
true);
while (true) {
String str = in.readLine();
if (str.equals("END"))
break;
System.out.println("Echoing: " + str);
out.println(str);
}
// Always close the two sockets...
} finally {
System.out.println("closing...");
socket.close();
}
} finally {
s.close();
}
}
}
客戶端:
package foo;
//: JabberClient.java
// Very simple client that just sends
// lines to the server and reads lines
// that the server sends.
import java.net.*;
import java.io.*;
public class Client {
public static void main(String[] args) throws IOException {
// Passing null to getByName() produces the
// special "Local Loopback" IP address, for542
// testing on one machine w/o a network:
InetAddress addr = InetAddress.getByName(null);
// Alternatively, you can use
// the address or name:
// InetAddress addr =
// InetAddress.getByName("127.0.0.1");
// InetAddress addr =
// InetAddress.getByName("localhost");
System.out.println("addr = " + addr);
Socket socket = new Socket(addr, Server.PORT);
// Guard everything in a try-finally to make
// sure that the socket is closed:
try {
System.out.println("socket = " + socket);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// Output is automatically flushed
// by PrintWriter:
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),
true);
for (int i = 0; i < 10; i++) {
out.println("howdy " + i);
String str = in.readLine();
System.out.println(str);
}
out.println("END");
} finally {
System.out.println("closing...");
socket.close();
}
}
}
運行時發現需要兩個控制檯Console來分別顯示:點擊 圖中 open console -- new console view 就會出現兩個控制檯了
然後將控制檯拖出,方便同時查看,然後在程序運行完成後擊 display selected console 來選擇要顯示的控制檯視圖
點