问答详情
源自:3-3 编程实现基于 TCP 的 Socke t通信之客户端

网络通信对话

为什么控制台不可以输入信息

控制台

package immoke网络通信;


import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.net.ServerSocket;

import java.net.Socket;


public class Server {


public static void main(String[] args) {

// TODO Auto-generated method stub

try {

ServerSocket serversocket=new ServerSocket(8998);

System.out.println("###服务器即将连接,等待客户端的连接###");

Socket socket=serversocket.accept(); 

InputStream is=socket.getInputStream();

InputStreamReader isr=new InputStreamReader(is);

BufferedReader br=new BufferedReader(isr);

String info;

while((info=br.readLine())!=null) {

System.out.println("我是服务器,客户端说:"+info);

}

socket.shutdownInput();

br.close();

is.close();

isr.close();

socket.close();

serversocket.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}


}

客户端

package immoke网络通信;


import java.io.IOException;

import java.io.PrintWriter;

import java.net.Socket;

import java.net.UnknownHostException;


import java.io.OutputStream;

public class Client {


public static void main(String[] args) {

// TODO Auto-generated method stub

try {

Socket socket=new Socket("localhost",8998);

OutputStream os=socket.getOutputStream();

PrintWriter pw=new PrintWriter(os);

pw.write("用户名:Mituzhifan,密码:123");

pw.flush();

socket.shutdownOutput();

pw.close();

os.close();

socket.close();

} catch (UnknownHostException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}


}


提问者:棨优 2019-10-01 23:32

个回答

  • 博博11
    2019-10-19 12:50:07

    你说的是想在控制台上交互,控制输出的信息么?