另外,如果你想连接Web,URL class和相关类(URLConnection,URLEncoder)可能比sokect更加合适,实际上,URLs 是对Web的一种相对高层的连接,sockets则作为底层实现
Reading from and writing to a Socket
package demo;
import java.io.*;
import java.net.*;
public class EchoClient {
public static void main(String args[]) throws IOException {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try{
echoSocket = new Socket("taranis", 7);
//write to the socket
out = new PrintWriter(echoSocket.getOutputStream(), true);
//read the socket
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
}catch (UnknownHostException e){
System.err.println("Don't know about host");
System.exit(1);
}catch (IOException e){
System.err.println("couldn't get I/O for the connection to taranis");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
Open a socket.
Open an input stream and output stream to the socket.
Read from and write to the stream 4. according to the server's protocol.
Close the streams.
Close the socket.
Writing the Server Side of a Socket
The Knock Knock Server