首页 > 编程语言 > 详细

java socket接口

时间:2017-10-07 22:44:07      阅读:272      评论:0      收藏:0      [点我收藏+]
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接口

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!