-
socket发送字符流,无法接收回复的流3
服务端:
- package socket;
- import java.io.IOException;
- import java.net.ServerSocket;
- import java.net.Socket;
- public class SocketServer {
- ServerSocket serverSocket = null;
- Socket socket = null;
- public SocketServer() {
- try {
- init();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- public void init() throws Exception {
- serverSocket = new ServerSocket(9999);
- }
- public void run() {
- try {
- while(true) {
- socket = serverSocket.accept();
- MyServer ms = new MyServer(socket);
- Thread td = new Thread(ms);
- td.start();
- }
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- SocketServer ss = new SocketServer();
- ss.run();
- }
- }
- package socket;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStreamWriter;
- import java.io.OutputStream;
- import java.io.PrintWriter;
- import java.net.Socket;
- import file.HandleFile;
- public class MyServer implements Runnable {
- Socket socket = null;
- PrintWriter pw = null;
- public MyServer(Socket socket) {
- this.socket = socket;
- }
- public void run() {
- // TODO Auto-generated method stub
- try {
- if(socket == null) {
- throw new Exception();
- }
- BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
- BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
- StringBuffer sb = new StringBuffer();
- String tmp = null;
- while((tmp = br.readLine()) != null) {
- sb.append(tmp);
- }
- System.out.println(sb.toString());
- pw = new PrintWriter(bw);
- pw.println("袁泉");
- pw.flush();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } finally {
- pw.close();
- }
- }
- }
客户端:
- package socket;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.io.OutputStreamWriter;
- import java.io.PrintWriter;
- import java.net.Socket;
- import file.HandleFile;
- public class SocketClient {
- Socket socket = null;
- FileOutputStream fops = null;
- OutputStream out = null;
- InputStream input = null;
- PrintWriter pw = null;
- SocketClient() {
- try {
- init();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- private void init() throws Exception {
- socket = new Socket("127.0.0.1", 9999);
- }
- public void run() {
- try {
- BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
- pw = new PrintWriter(bw);
- pw.println("夏雨");
- pw.flush();
- BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
- StringBuffer sb = new StringBuffer();
- String temp = null;
- while((temp = br.readLine()) != null) {
- sb.append(temp);
- }
- System.out.println(sb.toString());
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } finally {
- pw.close();
- }
- }
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- SocketClient sc = new SocketClient();
- sc.run();
- }
- }
不知道哪里阻塞了,消息也没发送过去
2010年5月08日 14:56
4个答案按时间排序按投票排序
-
注意用PrintWriter,在往流中写时,要记得flush,也可以用new PrintWriter(writer,true)让它自动flush。
还有,服务器端和客户端的动作要一致,服务器先写,那么客户就先读,先写就是socket.getOutputStream()在socket.getInputStream()之前调用,反之亦然。否则会造成阻塞。
以下代码供参考:
- package org.zergle.test.socket.server;
- import java.net.InetAddress;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.util.Date;
- import java.util.ArrayList;
- import java.util.List;
- /**
- * 服务器
- *
- * @author Johnson Lee
- *
- */
- public class Server {
- private boolean running;
- private List<ConnectedClient> clients;
- private ServerSocket svrSocket;
- public Server() {
- this.running = true;
- this.clients = new ArrayList<ConnectedClient>();
- }
- public boolean isRunning() {
- return running;
- }
- public void run() {
- try {
- this.svrSocket = new ServerSocket(9090);
- System.err.println("Server started on "
- + new java.sql.Date(new Date().getTime()));
- while (running) {
- Socket cltSocket = this.svrSocket.accept();
- // 保存客户端的连接
- InetAddress ip = cltSocket.getInetAddress();
- int port = cltSocket.getPort();
- ConnectedClient client = new ConnectedClient(ip, port);
- this.clients.add(client);
- System.err.println(ip + " connected.");
- // 为每个客户端开一个线程
- new Thread(new RequestProcessor(this, cltSocket)).start();
- }
- } catch (Exception e) {
- this.running = false;
- }
- }
- /**
- * 连接到服务器端的客户端
- *
- * @author Johnson Lee
- *
- */
- private static class ConnectedClient {
- public InetAddress ip;
- public int port;
- public ConnectedClient(InetAddress ip, int port) {
- super();
- this.ip = ip;
- this.port = port;
- }
- @Override
- public boolean equals(Object obj) {
- if (obj instanceof ConnectedClient) {
- ConnectedClient c = (ConnectedClient) obj;
- return c.ip.equals(this.ip) && c.port == this.port;
- }
- return false;
- }
- }
- /**
- * @param args
- */
- public static void main(String[] args) {
- new Server().run();
- }
- }
- package org.zergle.test.socket.server;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.InetAddress;
- import java.net.Socket;
- import java.net.SocketException;
- /**
- * 服务器端用于处理客户连接的处理器
- *
- * @author Johnson Lee
- *
- */
- public class RequestProcessor implements Runnable {
- private Server server;
- private Socket socket;
- public RequestProcessor(Server server, Socket socket) {
- this.server = server;
- this.socket = socket;
- }
- @Override
- public void run() {
- if (this.server.isRunning() && this.socket != null
- && this.socket.isConnected()) {
- InetAddress ip = this.socket.getInetAddress();
- BufferedReader br = null;
- PrintWriter pw = null;
- String line = null;
- try {
- InputStream is = this.socket.getInputStream();
- br = new BufferedReader(new InputStreamReader(is));
- pw = new PrintWriter(this.socket.getOutputStream(), true);
- while ((line = br.readLine()) != null) {
- System.out.println(line);
- pw.println("服务器自动回复 ^_^ ");
- pw.flush();
- }
- } catch (SocketException e) {
- System.err.println("客户端 " + ip + " 已断开连接");
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- if (br != null) {
- br.close();
- br = null;
- }
- } catch (IOException e) {
- }
- }
- }
- }
- }
- package org.zergle.test.socket.client;
- 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.InetSocketAddress;
- import java.net.Socket;
- /**
- * 客户端
- *
- * @author Johnson Lee
- *
- */
- public class Client {
- private InetSocketAddress svrAddress;
- private Socket svrSocket;
- public Client(String host, int port) {
- this.svrAddress = new InetSocketAddress(host, port);
- }
- public void connect() throws IOException {
- this.svrSocket = new Socket(svrAddress.getAddress(), svrAddress
- .getPort());
- }
- public boolean isClosed() {
- return this.svrSocket == null || this.svrSocket.isClosed();
- }
- public InputStream getInputStream() throws IOException {
- return this.svrSocket.getInputStream();
- }
- public OutputStream getOutputStream() throws IOException {
- return this.svrSocket.getOutputStream();
- }
- /**
- * @param args
- */
- public static void main(String[] args) {
- BufferedReader br = null;
- PrintWriter pw = null;
- String line = null;
- try {
- final Client c = new Client("127.0.0.1", 9090);
- c.connect();// 连接服务器
- try {
- br = new BufferedReader(new InputStreamReader(System.in));
- pw = new PrintWriter(c.getOutputStream(), true);
- new Thread(new ResponseProcessor(c)).start();
- while (!c.isClosed()) {
- line = br.readLine();
- pw.println(line);
- }
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- if (br != null) {
- br.close();
- br = null;
- }
- if (pw != null) {
- pw.close();
- pw = null;
- }
- } catch (IOException e) {
- }
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- package org.zergle.test.socket.client;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.SocketException;
- /**
- * 服务端响应处理器
- *
- * @author Johnson Lee
- *
- */
- public class ResponseProcessor implements Runnable {
- private Client client;
- public ResponseProcessor(Client c) {
- super();
- this.client = c;
- }
- @Override
- public void run() {
- BufferedReader br = null;
- PrintWriter pw = null;
- String line = null;
- try {
- br = new BufferedReader(new InputStreamReader(client
- .getInputStream()));
- pw = new PrintWriter(System.out, true);
- while (!client.isClosed()) {
- line = br.readLine();
- pw.println(line);
- }
- } catch (SocketException e) {
- if (!client.isClosed()) {
- System.err.println(e);
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
2010年5月10日 15:16
-
- while((tmp = br.readLine()) != null) {
- sb.append(tmp);
- }
这行阻塞了,客户端的writer只是flush没有关闭,这个方法会一直等待知道客户输出流关闭。
MyServer类改成:
- ...
- while ((tmp = br.readLine()) != null) {
- System.out.println(tmp);
- sb.append(tmp);
- pw = new PrintWriter(bw,true);
- pw.println("袁泉");
- }
SockerClient改成:
- BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
- BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
- pw = new PrintWriter(bw, true);
- pw.println("夏雨");
- BufferedInputStream bin = new BufferedInputStream(System.in);
- sc = new Scanner(bin);
- StringBuffer sb = new StringBuffer();
- String temp = null;
- while ((temp = br.readLine()) != null) {
- System.out.println(temp);
- String line = sc.nextLine();
- pw.println(line);
- }
即可实现互发消息2010年5月09日 00:46
-
你的server和client都用了PrintWriter的readLine()方法,这个方法阻塞了,因为你两边发送的都是几个字符,其中没有换行 ('\n')或者回车 ('\r'),因此,两边的这个方法就一直阻塞着。
2010年5月08日 23:59
-
PrintWriter 的 println 是打印字符串。在socket编程中使用的是write。。
=============
注意了write使用,字符串必须加上换行(“\n”)2010年5月08日 23:46