怎么实现从控制台输入字符串然后传给服务器端呢?
//服务器端public class Server {
public void strat() throws Exception{
ServerSocket ss = new ServerSocket(8899);
while(true){
Socket socket = ss.accept();
System.out.println(socket);
Hunter thread = new Hunter(socket);
thread.start();
}
}
public class Hunter extends Thread{
private Socket socket;
public Hunter(Socket socket){
this.socket = socket;
}
@Override
public void run(){
try{
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = br.readLine();
System.out.println(line);
OutputStreamWriter osw = new OutputStreamWriter(os);
PrintWriter pw = new PrintWriter(osw);
pw.println("小诺");
pw.flush();
socket.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception{
System.out.println("我是服务器端");
Server1 server = new Server1();
server.strat();
}
}
客户端
import
import
import
import
import
import
import
public class Client {
public void request() throws Exception{
Socket socket = new Socket("localhost",8899);
System.out.println(socket);
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
PrintWriter pw = new PrintWriter(osw);
//就是想从这里打印自己输入的文字传到服务器端
pw.println("我可以假装看不见,也可以偷偷的想念");
pw.flush();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = br.readLine();
System.out.println(line);
socket.close();
}
public static void main(String[] args) throws Exception{
System.out.println("你好,我是客户端");
Client client = new Client();
client.request();
}
}