java socket
今天尝试java socket ,碰到了问题,服务器端和客户端可以连通,服务器端收到客户端链接后,给客户端发送一个信息,但是客户端不知道为什么收到这个信息,貌似开在readline那里了。
有人能帮忙看看吗:
客户端
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.net.Socket;import java.net.SocketException;import java.net.UnknownHostException;public class mainJava { //static String ip = "127.0.0.1";// static int port = 8888; /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub try { Socket sc= new Socket ("127.0.0.1",8888); if(sc!=null) { sc.setKeepAlive(true); OutputStreamWriter os = new OutputStreamWriter(sc.getOutputStream()); BufferedWriter bw = new BufferedWriter(os); //将字节流包装为字符流(根据大家需求而定) bw.write("发送一个请求给服务器"); //写入请求信息 BufferedReader br = getReader(sc); //sc. String tmpstr = ""; boolean isFinish = false; while(isFinish==false) { tmpstr=br.readLine(); if(tmpstr!=null) { if(tmpstr=="end") { isFinish = true; }else { System.out.println(tmpstr); } }else { } System.out.println("收到消息"); } } } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch(SocketException e) { System.out.println("连接失败"); //e.printStackTrace(); e.getCause(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static BufferedReader getReader(Socket socket) throws IOException { InputStream in = socket.getInputStream(); return new BufferedReader(new InputStreamReader(in)); } }
import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.IOException;import java.io.OutputStreamWriter;import java.net.ServerSocket;import java.net.Socket;public class testSocket { /** * @param args */ static int port = 8888; public static void main(String[] args) { // TODO Auto-generated method stub try { ServerSocket listensocket = new ServerSocket(port); Socket tmp = null; int counter = 1; boolean flag = true; System.out.println("-------->Server"); while(flag) { tmp = listensocket.accept(); OutputStreamWriter os = new OutputStreamWriter(tmp.getOutputStream()); BufferedWriter bw = new BufferedWriter(os); bw.write("发送给客户端一个相应"); bw.flush(); //BufferedReader br = getReader(sc); counter++; if(counter == 10) { flag = false; } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}
bw.write("发送给客户端一个相应"); bw.writr("\n");
[解决办法]
1. 我用了bw.close()也可以,为什么readline在接收一次之后,就开始返回null
bw.close() 意味着都关闭流了,readLine当然啥都读不到了。。。