ServerSocket s = new ServerSocket(2000);
try{
while(true){
Socket socket = s.accept();
try{
BufferedReader in =
new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
StringBuffer sb = new StringBuffer();
int c;
while( (c = in.read()) != -1 ){
char ch = (char)c;
sb.append(ch);
}
System.out.println(sb.toString());
}catch(IOException e){
socket.close();
}finally{
socket.close();
}
}//while
}finally{
s.close();
}//try
}//main
}
此程式主要用 Servers 来进行无限监听,而 Clients 是客户机发送程式,他们的端
口全采用 2000。
eg2:
//UDPsend.java
import java.io.*;
import java.net.*;
/**
* This class sends the specified text or file as a datagram to the
* specified port of the specified host.
**/