Java网络编程,客户端和服务端相互发送信息,可是我写的双方都没读到对方发送的信息,代码如下
3个回答
展开全部
把 System.out.println(reader.readLine()); 这句去掉
把 bw.close(); 去掉
下面是你的代码,运行试试
客户端
package com.pzr.demo20161021;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class demo3 {
public static void main(String args[]){
try {
Socket socket = new Socket("127.0.0.1",8888);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
while(true){
System.out.println("请输入消息:");
// System.out.println("服务器发过来的消息:"+reader.readLine());
bw.write(br.readLine());
bw.newLine();
bw.flush();
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务端
package com.pzr.demo20161021;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class demo4 {
public static void main(String args[]){
try {
ServerSocket serverSocket =new ServerSocket(8888);
Socket socket = serverSocket.accept();
System.out.println(socket.getInetAddress().getHostAddress()+"已连接");
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter witer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
String string = null;
while((string = reader.readLine()) != null){
System.out.println(string);
}
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while((string = br.readLine()) != null){
witer.write(string);
witer.newLine();
witer.flush();
}
reader.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
tcp的东西忘记了,感觉应该是端口的问题。
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询