码迷,mamicode.com
首页 > 其他好文 > 详细

Socket网络编程(三)

时间:2018-11-29 01:18:16      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:put   style   shutdown   str   ==   通讯   客户端   exce   stream   

TCP协议网络通讯案例(http协议)

1、创建TcpServer(tcp服务端)

package com.cppdy.tcp;

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

//tcp服务端
public class TcpServer {

    public static void main(String[] args) throws Exception {

        System.out.println("tcp服务端启动啦……");
        ServerSocket serverSocket = new ServerSocket(8080);
        try {
            // 会阻塞在这里,等待连接
            Socket accept = serverSocket.accept();

            InputStream inputStream = accept.getInputStream();

            byte[] bytes = new byte[1024];

            int length = inputStream.read(bytes);

            String result = new String(bytes, 0, length);

            System.out.println("服务端接收到客户端发送的消息:" + result);

            OutputStream outputStream = accept.getOutputStream();

            PrintWriter printWriter = new PrintWriter(outputStream);

            printWriter.println("服务器收到消息了,这是服务器自动反馈……");

            printWriter.flush();

            accept.shutdownOutput();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            serverSocket.close();
        }
    }

}

2、创建TcpClient(tcp客户端)

package com.cppdy.tcp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

//tcp客户端
public class TcpClient {

    public static void main(String[] args) throws Exception {

        Socket socket = new Socket("127.0.0.1", 8080);

        try {
            OutputStream outputStream = socket.getOutputStream();

            String msg = "吹泡泡的魚";

            outputStream.write(msg.getBytes());

            System.out.println("客户端发送消息完毕……");

            InputStream inputStream = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));

            String result = br.readLine();

            System.out.println("客户端==》服务器返回的结果:" + result);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            socket.close();
        }
    }

}

 

Socket网络编程(三)

标签:put   style   shutdown   str   ==   通讯   客户端   exce   stream   

原文地址:https://www.cnblogs.com/cppdy/p/10035714.html

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