首页 > 编程语言 > 详细

九:JAVA Socket编程

时间:2020-12-04 08:55:23      阅读:25      评论:0      收藏:0      [点我收藏+]

客户端

技术分享图片
package TestSocket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;



public class SocketClient {
    public static String readLine = "hello";
    //1.建立一个socket
    //2.连接
    //3.发送数据
    //4.获取数据
    @SuppressWarnings("resource")
    public static void main(String[] args) throws Exception, Exception {
        Socket socket = new Socket("localhost",8899);
        
        
        BufferedReader systemIn = new BufferedReader(new InputStreamReader(System.in));
        BufferedReader socketIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        PrintWriter socketOut = new PrintWriter(socket.getOutputStream());
        
        
        while (readLine != "bye") {
            
            System.out.print("Client:");
            readLine = systemIn.readLine();
            socketOut.println(readLine);
            socketOut.flush();
            
            String inTempString = socketIn.readLine();
            System.out.println(inTempString);
            System.out.println("Server");
            
        }
    }
}
客户端

服务端

技术分享图片
package TestSocket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.Scanner;





public class SocketServer {
    public static String readLine = "hello";

    public static void main(String[] args) throws Exception {
        //创建server服务器绑定端口号
        ServerSocket server = new ServerSocket(8899);

        // 调用accept镜像阻塞,当有申请连接时会打开阻塞并返回socket
        System.out.println("hello");
        Socket accept = server.accept();
        
        //获取服务器输入  inputStreamReader是字节流转换成字符流
        BufferedReader systemIn = new BufferedReader(new InputStreamReader(System.in));
        BufferedReader sockerIn = new BufferedReader(new InputStreamReader(accept.getInputStream()));
        //printwriter具有自动行刷新的缓冲字符输出流,特点是可以按行写出字符串,并且可以自动行刷新。
        PrintWriter socketOut = new PrintWriter(accept.getOutputStream());
        
        while (readLine != "bye") {
            String inTempString = sockerIn.readLine();
            System.out.print("Client:");
            System.out.println(inTempString);
            System.out.println("Server");
            readLine = systemIn.readLine();
            
            socketOut.println(readLine);
            socketOut.flush();
        }
    }
}
服务端

 

九:JAVA Socket编程

原文:https://www.cnblogs.com/BookMiki/p/14083091.html

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