服务端:
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 ServerSocket {
public static void main(String[] args) {
try {
createServerSocket();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void createServerSocket() throws IOException {
ServerSocket serverSocket = new ServerSocket(8189);
Socket socket = serverSocket.accept();// wait for client connection
while (true) {
BufferedReader in = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream());
while (true) {
String str = in.readLine();
System.out.println("server:" + str);
out.println("client receive" + str);
out.flush();
if (str.equals("exit"))
break;
}
socket.close();
}
}
}
客户端:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class ClientSocket {
private static final String URL = "localhost";
private static final int PORT = 8189;
/**
* create client socket
*
* @throws IOException
* @throws UnknownHostException
*
*/
private static void createClientSocket() throws UnknownHostException,
IOException {
Socket clientSocket = new Socket(URL, PORT);
BufferedReader in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream());
BufferedReader wt = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String str = wt.readLine();
out.println("client send:" + str);
out.flush();
if (str.equals("end")) {
break;
}
System.out.println(in.readLine());
}
clientSocket.close();
}
public static void main(String[] args) {
try {
createClientSocket();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}