Java网络编程小结_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > Java网络编程小结

Java网络编程小结

 2018/8/21 15:22:38  NOthingAj  程序员俱乐部  我要评论(0)
  • 摘要:简单的Java网络编程客户端和服务器的交流代码服务器:importjava.net.*;importjava.io.*;importjava.lang.*;publicclassServerextendsThread{privateServerSocketserverSocket;publicstaticvoidmain(String[]args){intport=Integer.parseInt(args[0]);try{Threadt=newServer(port);t.run();
  • 标签:Java 网络 编程

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

?

服务器:

class="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中获取用户的真实ip 下一篇: 没有下一篇了!
发表评论
用户名: 匿名