Socket和服务端连接
服务端从Mina换了 Netty
但是我是用原生Socket写的 就是那种很原始的那种教科书级的
但是连接不上
一直是数据能发送过去
但是接收不到服务端的数据
终于让我找到了原因下面上代码
public class MySocketClient { private Socket soc = null; private String server = ""; private int port = 0; public static void main(String[] args) { try { //创建一个客户端socket Socket socket = new Socket("localhost",9999); //向服务器端传递信息 OutputStream ots = socket.getOutputStream(); PrintWriter pw = new PrintWriter(ots); pw.write("123456"); pw.flush(); //关闭输出流 socket.shutdownOutput(); //获取服务器端传递的数据 InputStream is = socket.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String info = null; while((info=br.readLine())!=null){ System.out.println("我是客户端,服务器说:"+info); } //关闭资源 br.close(); isr.close(); is.close(); pw.close(); ots.close(); socket.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
大家注意 socket.shutdownOutput();
这句话,不能少了shutdownOutput()不然,就会造成客户端只有在服务端关闭后才能收到数据的bug
个人感觉因为你不主动关闭socket流,服务端一直以为你在发送数据,占用了你们俩的链接通道所致,socket的通信机制所决定