猿问

socket 怎么实现服务器与客户端不停的互发消息呢?

在 java Socket应用的 3-4节 我把老师的代码修改了一下可以手动输入文字让对面的服务器/客户端接受,

下面是代码:

//客户端

package 通讯;


import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.io.OutputStreamWriter;

import java.io.PrintStream;

import java.net.Socket;

import java.util.Scanner;


public class client {

public static void main(String[] args) {

try {


Socket socket = new Socket("127.0.0.1", 8885);

while (true) {  //死循环重复步骤

OutputStream os = socket.getOutputStream();

PrintStream bw = new PrintStream(os);

Scanner input = new Scanner(System.in);

System.out.println("你想对对面的服务器说些什么");

bw.print(input.next());//从键盘输入读取一行 打印到输出流

bw.flush();

socket.shutdownOutput();


InputStream is = socket.getInputStream();

InputStreamReader isr = new InputStreamReader(is);

BufferedReader br = new BufferedReader(isr);

String s;

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

System.out.println("服务器端说:" + s);

}

socket.shutdownInput();


br.close();

isr.close();

is.close();

bw.close();

os.close();

}


} catch (IOException e) {

e.printStackTrace();

}


}

}


//服务器端

package 通讯;


import java.io.BufferedOutputStream;

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.io.PrintStream;

import java.io.PrintWriter;

import java.net.ServerSocket;

import java.net.Socket;

import java.util.Scanner;


public class server {

public static void main(String[] args) {

try {


ServerSocket serversocket = new ServerSocket(8885);

System.out.println("正在等待连接。。。。。。。");

Socket socket = serversocket.accept();

while(true){//死循环重复

InputStream is = socket.getInputStream();

InputStreamReader isr = new InputStreamReader(is);

BufferedReader br = new BufferedReader(isr);

String s;

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

System.out.println("客户端说" + s);

}

socket.shutdownInput();

OutputStream os = socket.getOutputStream();

PrintStream bw = new PrintStream(os);

Scanner input = new Scanner(System.in);

System.out.println("你想对面的客户机说些什么");

bw.print(input.next());//从键盘输入读取一行打印到输出流

bw.flush();

socket.shutdownOutput();

bw.close();

os.close();

br.close();

isr.close();

is.close();


}


} catch (IOException e) {

e.printStackTrace();

}


}


}

没加while死循环之前是,服务器等待请求,客户端发送一行文字,服务器接受后再发一行文字回去,程序结束。之后我又加了两个while死循环希望它能一直重复互发消息的步骤,但是出现了如下的异常,代码应该怎么修改才能实现我想要的不停的互发消息呢?   

http://img.mukewang.com/58f4ab6100017b0f03810228.jpg

http://img.mukewang.com/58f4ab610001e7f403330175.jpg


慕粉张张张
浏览 4717回答 1
1回答
随时随地看视频慕课网APP

相关分类

Java
我要回答