java 聊天程序,服务器怎么将客户发来的消息发给指定客户端?
客户端:publicclassClient{publicstaticvoidmain(String[]args)throwsException{Socketclient=...
客户端:
public class Client {
public static void main(String[] args) throws Exception {
Socket client = new Socket("localhost", 12345);
PrintStream ps = new PrintStream(client.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
boolean flag = true;
while (flag) {
String msg = input.readLine();
if("bye".equalsIgnoreCase(msg)){
flag = false;}
ps.println(msg);
String newMsg = reader.readLine();
System.out.println(newMsg);}
input.close();
client.close();}}
服务器:
public class Server {
public static void main(String[] args) throws Exception {
ServerSocket server = new ServerSocket(12345);
System.out.println("等待客户端连接");
boolean flag = true;
while (flag) {
Socket client = server.accept();
new Thread(new ECHOThread(client)).start();}
server.close();}}
多线程:
public class ECHOThread implements Runnable {
private Socket client;
public ECHOThread(Socket client) {
this.client = client;}
public void run() {
try {
BufferedReader input = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintStream ps = new PrintStream(client.getOutputStream());
while (true) {
String data = input.readLine();
System.out.println("-->" + data);
if (data == null) {break;}
String newData = "ECHO: " + data;
ps.println(newData);}
} catch (IOException e) {e.printStackTrace();}}} 展开
public class Client {
public static void main(String[] args) throws Exception {
Socket client = new Socket("localhost", 12345);
PrintStream ps = new PrintStream(client.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
boolean flag = true;
while (flag) {
String msg = input.readLine();
if("bye".equalsIgnoreCase(msg)){
flag = false;}
ps.println(msg);
String newMsg = reader.readLine();
System.out.println(newMsg);}
input.close();
client.close();}}
服务器:
public class Server {
public static void main(String[] args) throws Exception {
ServerSocket server = new ServerSocket(12345);
System.out.println("等待客户端连接");
boolean flag = true;
while (flag) {
Socket client = server.accept();
new Thread(new ECHOThread(client)).start();}
server.close();}}
多线程:
public class ECHOThread implements Runnable {
private Socket client;
public ECHOThread(Socket client) {
this.client = client;}
public void run() {
try {
BufferedReader input = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintStream ps = new PrintStream(client.getOutputStream());
while (true) {
String data = input.readLine();
System.out.println("-->" + data);
if (data == null) {break;}
String newData = "ECHO: " + data;
ps.println(newData);}
} catch (IOException e) {e.printStackTrace();}}} 展开
2个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询