简体   繁体   中英

How to send data in a java socket program without closing socket

i created a sever socket program to send a stream data to Apache spark.But data is received by spark after i close the socket or termination of program.i need to send data without closing socket and terminating program.

 import java.io.DataOutputStream;
 import java.net.ServerSocket;
 import java.net.Socket;
 import java.util.Scanner;

public class SocketServer {
public static void main(String[] args) {
    try {
        ServerSocket ss = new ServerSocket(9999);
        Socket s = ss.accept();// establishes connection

        DataOutputStream dout = new DataOutputStream(s.getOutputStream());
        Scanner scanner = new Scanner(System.in);
        String s1 = "";
        while (!s1.equals("end")) {
            s1 = scanner.next();
            dout.writeUTF(s1);
            dout.flush();
        }
     ss.close();
    } catch (Exception e) {r
        System.out.println(e);
    }
  }
}

i can send data in stream using nc server nc -lk 9999 .

EDIT -1 Tried with println

try {
        ServerSocket ss = new ServerSocket(6000);
        Socket s = ss.accept();// establishes connection

        OutputStream ostream = s.getOutputStream();
        PrintWriter pwrite = new PrintWriter(ostream, true);
        Scanner scanner = new Scanner(System.in);
        String s1 = "";
        while (!s1.equals("end")) {
            s1 = scanner.next();
            pwrite.println(s1);
            pwrite.flush();
        }
        ss.close();
    } catch (Exception e) {
        System.out.println(e);
    }

Still not working.

Please help..

Unless Apache Spark is (a) written in Java and (b) calling readUTF() you're using the wrong method to send. You should probably be using a println() method. You also need to close the accepted socket, as well as the server socket.

First of all you should only be instantiating dout once (before the start of the while loop).

Secondly I believe the way it works is that when reading from a socket stream it reads until the end of the stream is reached (ie socket is closed). To finish reading early you'd need to send an "end of stream" without closing it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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