集册 Java实例教程 从服务器读取消息

从服务器读取消息

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

702
从服务器读取消息
/** 时代Java公众号 - N o w J a  v a . c o m 提 供 **/

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.io.OutputStreamWriter;

import java.net.InetAddress;

import java.net.Socket;

import java.util.Scanner;


public class Client

{


  private static Socket socket;


  public static void main(String args[])

  {

    try

    {

      String s = "wow";

      Scanner sc = new Scanner(System.in);

      socket = new Socket("192.168.1.122", 1234);
      /* from 
      时 代 J a v a 公 众 号 - N o w J a v  a . c o m*/

      while(s != "exit"){

        OutputStream os = socket.getOutputStream();

        OutputStreamWriter osw = new OutputStreamWriter(os);

        BufferedWriter bw = new BufferedWriter(osw);

  

        s = sc.nextLine();      

  

        String sendMessage = s;

        bw.write(sendMessage);

        bw.flush();

        System.out.println("Message sent to the server : "+sendMessage);

  

        //Get the return message from the server

        InputStream is = socket.getInputStream();

        InputStreamReader isr = new InputStreamReader(is);

        BufferedReader br = new BufferedReader(isr);

        String message = br.readLine();

        System.out.println("Message received from the server : " +message);

      }

      

展开阅读全文