标签:
服务器采用BIO模式,每一个线程处理一个连接。问题出现在,如果使用BufferedReader去读取字符流,如果没有换行符的话,那么就会导致线程阻塞。
import java.io.*; import java.net.Socket; import java.net.InetAddress; import java.net.ServerSocket; import java.util.Scanner; class ServerSocketTest { public static void main(String[] args) { try { ServerSocket ss = new ServerSocket(6000); System.out.println("Server running, waitting for client to login ..."); Socket s = ss.accept(); OutputStream os = s.getOutputStream(); InputStream is = s.getInputStream(); os.write("Hello Wellcome\n".getBytes()); os.flush(); /* byte[] buf = new byte[1024]; int len = is.read(buf); System.out.println(new String(buf,0,len));*/ BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = null; while((line = br.readLine()) != null){ System.out.println(line); } os.close(); is.close(); s.close(); ss.close(); } catch (Exception e) { e.printStackTrace(); } } }
客户端程序。
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.InetAddress; import java.net.Socket; import java.net.UnknownHostException; public class SocketTest { public static void main(String[] args){ try { System.out.println(InetAddress.getLocalHost()); Socket s = new Socket(InetAddress.getLocalHost(), 6000); OutputStream os = s.getOutputStream(); PrintWriter pw = new PrintWriter(os); pw.write("username:fangying;password:123\n"); pw.flush(); InputStream is = s.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = null; while ((line = br.readLine()) != null) { System.out.println("client get :" + line); } br.close(); is.close(); pw.close(); os.close(); s.close(); } catch (Exception e) { e.printStackTrace(); } } }
标签:
原文地址:http://www.cnblogs.com/fangying7/p/4676484.html