编程语言
首页 > 编程语言> > Java基础-网络编程Server-Client通信(2)

Java基础-网络编程Server-Client通信(2)

作者:互联网

package com.hspedu.TestServerClient;

import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class MyServer {


    @Test
    public void startMyServer() throws IOException {
        ServerSocket serverSocket = new ServerSocket(8080);
        System.out.println("服务器Server正在监听8080端口...");
        Socket socket = serverSocket.accept();

        // 1.接收client信息
        InputStream inputStream = socket.getInputStream();
        byte[] bytes = new byte[1024];
        int readData = 0;
        while ((readData = inputStream.read(bytes)) != -1) {
            System.out.print(new String(bytes, 0, readData));
        }

        // 2.回复client信息
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("服务器 >>> 客户端:hello, client.".getBytes());
        socket.shutdownOutput();

        inputStream.close();
        outputStream.close();
        socket.close();
        serverSocket.close();
    }
}
package com.hspedu.TestServerClient;

import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class MyClient {


    @Test
    public void startMyClient() throws IOException {
        Socket socket = new Socket(InetAddress.getLocalHost(), 8080);

        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("客户端 >>> 服务器:hello, server".getBytes());
        socket.shutdownOutput();

        InputStream inputStream = socket.getInputStream();
        int readData = 0;
        byte[] bytes = new byte[1024];
        while ((readData = inputStream.read(bytes)) != -1) {
            System.out.println(new String(bytes, 0, readData));
        }

        outputStream.close();
        inputStream.close();
        socket.close();
    }
}

1、服务器server和客户端client相互收发信息:socket对象的getOutputStream、getInputStream方法

标签:java,socket,readData,bytes,Server,Java,Client,close,import
来源: https://www.cnblogs.com/kenantongxue/p/16173331.html