简体   繁体   English

Java服务器未从C#客户端接收字符串

[英]Java server does not receive String from C# client

I'm using HttpClient to send post requests to the server, but it does not execute it and just waits forever: 我正在使用HttpClient将发布请求发送到服务器,但是它不执行它,只是永远等待:

 static void Main(string[] args) {
        Console.WriteLine("Hello World!");
        postJsonAsync().Wait();

        //Does not continue
        Console.WriteLine("FINISHED");
    }

    private static async Task postJsonAsync() {
        var json = "TEST";
        var content = new StringContent(json);

        using (HttpClient client = new HttpClient()) {
            var response = await client.PostAsync("http://localhost:80", content);
        }
    }

This is my Java server that waits for requests: 这是我的Java服务器,它等待请求:

public static void main(String[] args) throws IOException {
     ServerSocket server = new ServerSocket(80);

        System.out.println("Server has started on 127.0.0.1:80.\r\nWaiting for a connection...");

        Socket client = server.accept();

        System.out.println("A client connected.");

    Thread thread = new Thread() {
        @Override
        public void run() {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                    .url("http://localhost:80")
                    .build();
                Response responses = null;

                try {
                    responses = client.newCall(request).execute();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                String jsonData;

                try {
                    jsonData = responses.body().string();
                    System.out.println(jsonData);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

        }
    };

    thread.start();

    System.in.read();
}

This is the stacktrace: 这是堆栈跟踪:

    Server has started on 127.0.0.1:80.
Waiting for a connection...
A client connected.
java.net.SocketTimeoutException: Read timed out
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.socketRead(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at okio.Okio$2.read(Okio.java:140)

    at okio.AsyncTimeout$2.read(AsyncTimeout.java:237)

    at okio.RealBufferedSource.indexOf(RealBufferedSource.java:355)

    at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:227)

    at okhttp3.internal.http1.Http1Codec.readHeaderLine(Http1Codec.java:215)
    at okhttp3.internal.http1.Http1Codec.readResponseHeaders(Http1Codec.java:189)
    at okhttp3.internal.http.CallServerInterceptor.intercept(CallServerInterceptor.java:88)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
    at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:45)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
    at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
    at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
    at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
    at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)

    at okhttp3.RealCall.execute(RealCall.java:77)

    at Server$1.run(Server.java:38)
Exception in thread "Thread-0" java.lang.NullPointerException
    at Server$1.run(Server.java:46)

What is the problem? 问题是什么?

the server supposed to be like that : 服务器应该是这样的:

public static void main(String[] args) throws IOException {
    ServerSocket server = new ServerSocket(9090);
    try {
        while (true) {
            new Runner(server.accept()).start();            
            }
    } finally {
        server.close();
    }
}

class Runner extends Thread {

    private Socket socket;

    public Runner(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            System.out.println("A client connected.");
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String line;
            Integer postDataI = 0;
            line = in.readLine();
            while ((line = in.readLine()) != null && (line.length() != 0)) {
                System.out.println("HTTP-HEADER: " + line);
                if (line.indexOf("Content-Length:") > -1) {
                    postDataI = new Integer(
                            line.substring(
                                    line.indexOf("Content-Length:") + 16,
                                    line.length())).intValue();
                }
            }
            String postData = "";
            if (postDataI > 0) {
                char[] charArray = new char[postDataI];
                in.read(charArray, 0, postDataI);
                postData = new String(charArray);
            }


            String httpResponse = "HTTP/1.1 200 OK\r\n\r\n" + Instant.now();
            OutputStream out = socket.getOutputStream();
            out.write(httpResponse.getBytes("UTF-8"));
            out.close();

        } catch (Exception ex) {
            String msg = ex.getMessage();
        } finally {
            try {
                socket.close();
            } catch (IOException ex) {
            }
        }
    }
}

and the client implemented in C# 和客户端在C#中实现

private static void Post()
    {
        using (var httpClient = new HttpClient())
        {
            httpClient.DefaultRequestHeaders.ExpectContinue = false;
            var content = new StringContent("test", Encoding.UTF8);
            var result = httpClient.PostAsync("http://localhost:9090", content).Result;
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM