import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
ServerSocket server = null;
Socket soc = null;
BufferedReader dis = null;
PrintWriter ps = null;
String clientSay = null;
try {
server = new ServerSocket(8001);
System.out.println("wait.....");
soc = server.accept();
System.out.println("finish connection!");
dis = new BufferedReader(new InputStreamReader(soc.getInputStream()));
ps = new PrintWriter(soc.getOutputStream(),true);
ps.println("Welcome!");
clientSay = dis.readLine();
while(!clientSay.equals("quit")){
System.out.println("client say:"+clientSay);
clientSay = dis.readLine();
}
System.out.println("client quit!");
} catch (IOException e) {
System.out.println("Error:"+e);
}finally{
try {
ps.close();
dis.close();
soc.close();
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
==========================================================
package socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) {
Socket soc = null;
BufferedReader br = null;
PrintWriter pw = null;
BufferedReader sys = null;
String sysStr = null;
try {
System.out.println("start connection...");
soc = new Socket("127.0.0.1",8001);
br = new BufferedReader(new InputStreamReader(soc.getInputStream()));
pw = new PrintWriter(soc.getOutputStream(),true);
sys = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Server say:"+br.readLine());
sysStr = sys.readLine();
while(!sysStr.equals("quit")){
pw.println(sysStr);
sysStr = sys.readLine();
}
pw.println(sysStr);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
sys.close();
pw.close();
br.close();
soc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}