日期:2014-05-20  浏览次数:20874 次

急急急求SOCKET代码 要求发送到指定IP和端口 然后接收到返回字段 会话结束!
急求代码 谢谢!!!

------解决方案--------------------
你指定的服务器是如何响应呢?

Java code


import java.io.*;
import java.net.*;


public class TestSocket {
    public static void main(String[] args) {
    String result = getResult("www.china.com", 80);
    System.out.println(result);
    }

    
    public static String getResult(String ip, int port) {
    Socket socket = null;
    BufferedReader bufferedReader = null;
    StringBuffer result = null;

    try {
        
        //建立连接
        socket = new Socket(ip, port);
        bufferedReader = new BufferedReader(new InputStreamReader(socket
            .getInputStream(), "GBK"));

        //发出请求
        OutputStream out = socket.getOutputStream();
        StringBuffer stringBuffer = new StringBuffer(
            "GET /index.html HTTP/1.1\r\n");
        stringBuffer.append("User-Agent: Java/1.6.0_20\r\n");
        //Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR
        stringBuffer.append("Host: www.pconline.com.cn:80\r\n");
        stringBuffer
            .append("Accept: text/html\r\n");//取html文本内容
        stringBuffer.append("Connection: Close\r\n");
        stringBuffer.append("\r\n");
        out.write(stringBuffer.toString().getBytes());

        //取得相应
        result = new StringBuffer();
        String tempString = null;
        while ((tempString = bufferedReader.readLine()) != null) {
        result.append(tempString);
        result.append("\r\n");
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
        if (bufferedReader != null)
            bufferedReader.close();
        if (socket != null)
            socket.close();
        } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        }
    }
    return result.toString();
    }

}