日期:2014-05-17  浏览次数:20630 次

Socket问题,网络可以连接上,但是返回值接收不到,求助!
Socket socket = new Socket(ip, port);
System.out.println("服务器连接成功");
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
PrintWriter pw = new PrintWriter(osw);
pw.println(msg+"\r\n\r\n"); 
pw.flush()

// 接收返回的结果
StringBuffer buffer = new StringBuffer();
InputStreamReader inputStreamReader=new InputStreamReader(socket.getInputStream());

BufferedReader rd = new BufferedReader(inputStreamReader);

String line;
while ((line = rd.readLine()) != null) {
String t = new String(line.getBytes(), "utf-8");
    buffer.append(t);
}
strRst = buffer.toString();

pw.close();
rd.close();
osw.close();
os.close();
socket.close();


我与对方的网络是可以通的,但是接收返回值得时候rd.readLine()一直为null的,求助!!
------解决方案--------------------
发送端怎么发送的,最好要一致
------解决方案--------------------
给你个例子看看。
发送端代码:
import java.net.*;
import java.io.*;

/**
 * UDPSender is an implementation of the Sender interface, using UDP as the transport protocol.
 * The object is bound to a specified receiver host and port when created, and is able to 
 * send the contents of a file to this receiver.
 *
 * @author Alex Andersen (alex@daimi.au.dk)
 */
public class TCPSender implements Sender{
    private File theFile;
    private FileInputStream fileReader;
    private Socket s;
    private int fileLength, currentPos, bytesRead, toPort, length;
    private byte[]  msg, buffer;
    private String toHost,initReply;
    private InetAddress toAddress;
    private OutputStream theOutstream; 
    private InputStream theInstream;

    /**
     * Class constructor.
     * Creates a new UDPSender object capable of sending a file to the specified address and port.
     *
     * @param address  the address of the receiving host
     * @param port    the listening port on the receiving host
     */
    public TCPSender(InetAddress address, int port) throws IOException{
toPort = port;
toAddress = address;
msg = new byte[8192];
buffer = new byte[8192];
s = new Socket(toAddress, toPort);
theOutstream =&