集册 Java实例教程 用Socket和ServerSocket问候服务器和客户端

用Socket和ServerSocket问候服务器和客户端

欢马劈雪     最近更新时间:2020-01-02 10:19:05

548
用Socket和ServerSocket问候服务器和客户端

import java.io.*;

import java.net.*;

import java.util.Scanner;/*from n o w j a v a . c o m - 时  代  Java*/


class GreetingServer{

  private static GreetingServer server;

  static int Port = 3535;

  static ServerSocket Socket;

  

  public GreetingServer(){

    try{

      Socket = new ServerSocket(setSocket());

    }catch(Exception e){

      System.out.println("Error: "+e.getMessage());

    }

  }

  

  private int setSocket(){

    Scanner in = new Scanner(System.in);

    System.out.print("Enter socket number:");

    Port = in.nextInt();

    System.out.println("Socket number "+Port+" created.");//n o w    j a v a  . c o m

    System.out.println("Listening...");

    return Port;

  }

  

  public static void main(String argv[]) throws Exception {

    server = new GreetingServer();

    String clientSentence;          

    String capitalizedSentence;          

    while(true){             

      Socket connectionSocket = Socket.accept();             

      BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));

      DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());             

 
展开阅读全文