标签:logs als new sock flush fail string host hand
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class Service { ServerSocket server; Socket socket; public Service() { //建立服务器 try { server = new ServerSocket(10086); System.out.println("start service"); onServer(); } catch (IOException e) { System.out.print("failed to start service"); } } private void onServer() { try { socket = server.accept(); //监听端口 BufferedReader in=new BufferedReader(new InputStreamReader(socket.getInputStream())); String line; //不断从已建立链接的socket接收数据 do{ line = in.readLine(); System.out.println("Client Say:" + line); } while(!line.equals("quit")); in.close(); socket.close(); server.close(); } catch (IOException e) { System.out.println("Error" + e); } } public static void main(String[] args) { Service s = new Service(); } }
客户端:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; public class Client { private Socket socket; public Client() { //连接服务器 try { socket = new Socket("localhost",10086); HandleInput(); } catch (IOException e) { System.out.println("failed to connect Service"); } } private void HandleInput() { try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter write = new PrintWriter(socket.getOutputStream()); String readline; do { readline = br.readLine(); write.println(readline); //写入输出端 write.flush();//刷新,发送 System.out.println(readline); } while (!readline.equals("quit!")); write.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { Client c = new Client(); } }
标签:logs als new sock flush fail string host hand
原文地址:http://www.cnblogs.com/gride-glory/p/7636005.html