java socket 简单通信

来源:互联网 发布:荣耀盒子电视直播软件 编辑:程序博客网 时间:2024/05/24 03:15

模拟socket通信,创建两个java类

  • ServerDemo

package com.example;

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

/**
* Created by zhangyinyuan on 2016/12/22.
*/
public class ServerDemo {
public static void main(String[] args) {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(121);

        while (true) {            System.out.println("开始阻塞等待请求");            Socket socket = serverSocket.accept();            InputStream inputStream = socket.getInputStream();            InetAddress inetAddress = socket.getInetAddress();            byte[] buf = new byte[1024];            int length = inputStream.read(buf);            String text = new String(buf, 0, length);            System.out.println("text:" + text + " inetAddress: " + inetAddress);            socket.close();        }    } catch (IOException e) {        e.printStackTrace();    } finally {        try {            serverSocket.close();        } catch (IOException e) {            e.printStackTrace();        }    }}

}

  • ClientDemo
package com.example;import java.io.IOException;import java.io.OutputStream;import java.net.Socket;public class ClientDemo {    public static void main(String[] args) {        Socket socket = null;        try {            socket = new Socket("10.141.2.99", 121);            OutputStream outputStream = socket.getOutputStream();            outputStream.write("tcp演示".getBytes());        } catch (IOException e) {            e.printStackTrace();        } finally {//            try {//                socket.close();//            } catch (IOException e) {//                e.printStackTrace();//            }        }    }}

至此,简单的通信已完成。
开始测试,注意:先运行ServerDemo,在运行ClientDemo。

1 0
原创粉丝点击