Java实现socket编程入门

这个博客展示了如何使用Java的Bio包创建一个简单的TCP服务器和客户端。服务器监听9999端口,接收客户端连接并读取输入,然后回显接收到的数据。客户端则连接到服务器,发送用户输入并打印服务器的响应。这是一个基础的网络通信示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package bio;

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

public class TCPserver {
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(9999);
        while(true){
            Socket socket = ss.accept();
            InputStream in = socket.getInputStream();
            byte[] bytes = new byte[1024];
            in.read(bytes);

            String cip = socket.getInetAddress().getHostAddress();
            System.out.println(cip + " say: " + new String(bytes).trim());

            OutputStream out = socket.getOutputStream();
            Scanner sc = new Scanner(System.in);
            System.out.print("请输入:");
            out.write(sc.nextLine().getBytes());
            socket.close();
        }
    }
}

package bio;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public class TcpClient {
    public static void main(String[] args) throws IOException {
        while (true){
            Socket socket = new Socket("127.0.0.1",9999);
            OutputStream out = socket.getOutputStream();
            System.out.print("请输入:");
            Scanner sc = new Scanner(System.in);
            out.write(sc.nextLine().getBytes());
            InputStream in = socket.getInputStream();
            byte[] bytes = new byte[1024];
            in.read(bytes);
            System.out.println(socket.getInetAddress().getHostAddress() + " : " + new String(bytes).trim());
            socket.close();

        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值