欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java网络编程小结

程序员文章站 2022-03-22 15:20:46
...

简单的Java网络编程客户端和服务器的交流代码

 

服务器:

import java.net.*;
import java.io.*;
import java.lang.*;


public class Server extends Thread{
    private ServerSocket serverSocket;
    public static void main(String[] args) {
        int port = Integer.parseInt(args[0]);

        try {
            Thread t = new Server(port); 
            t.run();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Server(int port) throws IOException{
        serverSocket = new ServerSocket(port);
        serverSocket.setSoTimeout(10000); // 超时后就阻塞该线程
    }

    public void run() {
        while(true) {
            try {
                System.out.println("等待远程连接,端口号为:" + serverSocket.getLocalPort() + "...");
                Socket server = serverSocket.accept(); // 等待客户端的连接
                
                System.out.println("远程主机地址:" + server.getRemoteSocketAddress());
                DataInputStream in = new DataInputStream(server.getInputStream());
                System.out.println(in.readUTF());

                DataOutputStream out = new DataOutputStream(server.getOutputStream());
                // 将服务器地址写回客户端 
                out.writeUTF("服务器地址为:" + server.getLocalSocketAddress() + ", 连接结束..."); 
                server.close();
            } catch (SocketTimeoutException se) {
                System.out.println("连接超时...");
                break;
            } catch (IOException ie) {
                ie.printStackTrace();
                break;
            }
        }
    }
}

 

客户端:

import java.net.*;
import java.io.*;
import java.lang.*;

public class Client {

    public static void main(String[] args) {
        String serverName = args[0];
        int port = Integer.parseInt(args[1]);

        try {
            System.out.println("连接到主机:" + serverName + ",端口号:" + port);

            Socket client = new Socket(serverName, port);
            System.out.println("远程主机地址:" + client.getRemoteSocketAddress());

            OutputStream outServer = client.getOutputStream();
            DataOutputStream out = new DataOutputStream(outServer);

            out.writeUTF("Hello from " + client.getLocalSocketAddress());
            InputStream inFromServer = client.getInputStream();
            DataInputStream in = new DataInputStream(inFromServer);
            System.out.println("服务器响应: " + in.readUTF());
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

相关标签: Java