client -- server发送过程中,涉及的输入流输出流:
需要注意的是:先运行服务器端,再进行客户端。
http://blog.csdn.net/qq7342272/article/details/9698413 (值得推荐的好文)
public class SocketServer { public static void main(String[] args) {
SocketServer socketServer = new SocketServer(); socketServer.startServer(); } public void startServer() { ServerSocket serverSocket = null; Socket socket = null; try {
//1.建立一个服务器端,绑定指定端口 serverSocket = new ServerSocket(9898); System.out.println("server started.."); while (true) {
//2.等待客户端的连接。如果有客户端接入,则执行下面的代码;没有客户端接入,在这里阻塞。 socket = serverSocket.accept();
// 如果有客户端接入,在此方法执行客户端和服务器数据传输的操作。 manageConnection(socket); } } catch (Exception e) { e.printStackTrace(); } finally { try { socket.close(); serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } public void manageConnection(final Socket socket) { new Thread(new Runnable() { @Override public void run() { BufferedReader reader = null; BufferedWriter writer =null; try { System.out.println("client " + socket.hashCode() + " connedted");
//3.从网络->内存 in 获得输入流 reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//3.从内存->网络 out 获得输出流 writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); String receivedMsg;
//4.得到客户端发来的消息 while ((receivedMsg = reader.readLine()) != null) { System.out.println("client " + socket.hashCode() + ": " + receivedMsg);
//4.向客户端写出消息 writer.write("server reply: " + receivedMsg + " "); writer.flush(); } } catch (IOException e) { e.printStackTrace(); } finally {
//5.关闭资源 try { reader.close(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } } }).start(); } }
public class SocketClient { public static void main(String[] args) { SocketClient client = new SocketClient(); client.start(); } public void start() { BufferedReader inputReader = null; BufferedReader reader = null; BufferedWriter writer = null; Socket socket = null; try {
//1.建立客户端socket连接,指定服务器位置及端口 socket = new Socket("127.0.0.1", 9898);
//2.从网络->内存 in reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//2.从内存->网络 out writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
inputReader = new BufferedReader(new InputStreamReader(System.in)); startServerReplyListener(reader); String inputContent; int count = 0;
while (!(inputContent = inputReader.readLine()).equals("bye")) {
//3.向客户端发送消息 writer.write(inputContent); if (count % 2 ==0) { writer.write(" "); } count++; writer.flush(); } } catch (Exception e) { e.printStackTrace(); } finally {
//4.关闭资源 try { reader.close(); writer.close(); inputReader.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } public void startServerReplyListener(final BufferedReader reader) { new Thread(new Runnable() { @Override public void run() { try { String response;
//3.得到客户端发来的消息 while ((response = reader.readLine()) != null) { System.out.println(response); } } catch (IOException e) { e.printStackTrace(); } } }).start(); } }