从服务器向客户端发送数据?

时间:2019-04-03 08:56:50

标签: java android sockets tcp serversocket

我在此代码中遇到问题,客户端可以向服务器发送消息,但是它没有收到从服务器发送的消息,我已经调试了服务器代码,它可以执行所有应有的操作,但是客户端可以执行所有操作代码直到message = br.readLine(),然后一直粘贴在那里

服务器代码

    package server; 
    import java.io.BufferedReader;
    import java.io.EOFException;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.ServerSocket;
    import java.net.Socket;
    public class server {
    static Socket s;
    static ServerSocket ss;
    static InputStreamReader isr;
    static BufferedReader br;
    static String message;
    static PrintWriter pw;
    public server(){
try {
    ss=new ServerSocket(8080);
    while(true){
        s=ss.accept();
        isr=new InputStreamReader(s.getInputStream());
        br=new BufferedReader(isr);
        message=br.readLine();
        System.out.println(message);
        pw=new PrintWriter(s.getOutputStream(),true);
        pw.write("returned back from server to client");
        System.out.println("message sent");
        pw.flush();
        pw.close();
        isr.close();
        s.close();
    }
} catch (EOFException eofException) {
    // TODO Auto-generated catch block
    eofException.printStackTrace();
}catch(IOException e){
    e.printStackTrace();
}
 }
    public static void main(String[]args){
server s=new server();
  }
  }

客户代码

    package com.example.myapplication;
    import android.os.AsyncTask;
    import java.io.BufferedReader;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.Socket;

    public class ClientSender extends AsyncTask<String,Void,Void> {
Socket s;
DataOutputStream dos;
InputStreamReader isr;
BufferedReader br;
PrintWriter pw;
@Override
protected Void doInBackground(String... voids) {
    String message = voids[0];
    try {
        System.out.println("1");

        s = new Socket("0.0.0.0", 8080);
        pw = new PrintWriter(s.getOutputStream());
        pw.write(message);
        pw.flush();
        pw.close();
        s.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        System.out.println("2");
        s = new Socket("0.0.0.0", 8080);
        System.out.println("connected to the server");
        isr = new InputStreamReader(s.getInputStream());
        System.out.println("3");
        br = new BufferedReader(isr);
        System.out.println("4");
        message = br.readLine();
        System.out.println(message);
        isr.close();
        s.close();
        System.out.println("5");
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}
}

1 个答案:

答案 0 :(得分:-1)

我建议您使用Socket.IO而不是编写自己的套接字客户端。这是一个经过充分测试并有据可查的lib。这将使您的生活更加轻松。