Java Socket例程1
HelloServer.java
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class HelloServer{
public static void main(String args[]) throws IOException{
ServerSocket serversocket = null;
PrintWriter out = null;
try{
serversocket = new ServerSocket(9999);
}
catch(IOException e)
{
System.err.println("Could not listen on port:9999");
System.exit(1);
}
Socket clientsocket = null;
try{
clientsocket = serversocket.accept();
}
catch(IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
out = new PrintWriter(clientsocket.getOutputStream(),true);
out.println("hello world");
clientsocket.close();
serversocket.close();
}
}
HelloClient.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
public class HelloClient{
public static void main(String args[]) throws IOException{
Socket hellosocket = null;
BufferedReader in = null;
try{
hellosocket = new Socket("localhost",9999);
in = new BufferedReader(new InputStreamReader(hellosocket.getInputStream()));
}
catch(UnknownHostException e){
System.err.println("Don't know about host:localhost");
System.exit(1);
}
catch(IOException e)
{
System.err.println("Count't get I/O for the connection.");
System.exit(1);
}
System.out.println(in.readLine());
in.close();
hellosocket.close();
}
}
实现功能:先启动服务器,再启动客户端.连接成功之后,服务器给向客户端发送Hello World!
欢迎访问:wenhao.ink