码迷,mamicode.com
首页 > 编程语言 > 详细

java socket接口

时间:2017-10-07 22:52:09      阅读:276      评论:0      收藏:0      [点我收藏+]

标签:logs   als   new   sock   flush   fail   string   host   hand   

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接口

标签:logs   als   new   sock   flush   fail   string   host   hand   

原文地址:http://www.cnblogs.com/gride-glory/p/7636005.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!