java socket接口
Posted 暗影蔽日
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java socket接口相关的知识,希望对你有一定的参考价值。
PrintWriter write = new PrintWriter(socket.getOutputStream()); //获取socket的输出流
write.flush();//发送数据,刷新输出流
InputStreamReader in =new new InputStreamReader(socket.getInputStream()); //获取socket的输入流
服务器端:
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(); } }
以上是关于java socket接口的主要内容,如果未能解决你的问题,请参考以下文章