• 编写serversocket简单示例1


    package j2se.core.net.tcp;

    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.net.ServerSocket;
    import java.net.Socket;

    public class Server {
    public static void main(String[] args) throws IOException {
    ServerSocket server = new ServerSocket(8888);
    System.out.println("服务器启动中...");

    while(true) {
    // 主线程会一直阻塞到客户连接的传入
    Socket socket = server.accept();

    DataOutputStream output = new DataOutputStream(
    socket.getOutputStream());

    output.writeUTF("IP:" + socket.getInetAddress());
    output.writeUTF("PORT:" + socket.getPort());

    output.flush();
    output.close();
    socket.close();
    }
    }
    }

    package j2se.core.net.tcp;

    import java.io.DataInputStream;
    import java.io.IOException;
    import java.net.Socket;
    import java.util.Scanner;

    public class Client {
    public static void main(String[] args) throws IOException {
    Scanner scan = new Scanner(System.in);
    System.out.println("请输入服务器地址:");
    String ip = scan.nextLine();
    System.out.println("请输入服务器端口:");
    int port = scan.nextInt();

    Socket socket = new Socket(ip,port);
    DataInputStream input = new DataInputStream(socket.getInputStream());
    try
    {
    while (true) {
    System.out.println(input.readUTF());
    }
    }catch(Exception ex){
    //ex.printStackTrace();
    }finally
    {
    input.close();
    socket.close();
    }
    }
    }

  • 相关阅读:
    hdu 5119 Happy Matt Friends
    hdu 5128 The E-pang Palace
    hdu 5131 Song Jiang's rank list
    hdu 5135 Little Zu Chongzhi's Triangles
    hdu 5137 How Many Maos Does the Guanxi Worth
    hdu 5122 K.Bro Sorting
    Human Gene Functions
    Palindrome(最长公共子序列)
    A Simple problem
    Alignment ( 最长上升(下降)子序列 )
  • 原文地址:https://www.cnblogs.com/angel512/p/5868144.html
Copyright © 2020-2023  润新知