java socket 简单通信

模拟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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值