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(); } }