Why can't streaming connect to the Java socket client? - apache-spark

I am studying Spark streaming to process real time data, and I built the example wordCount of spark streaming, and I can run the example after:
/bin/run-example org.apache.spark.streaming.examples.JavaNetworkWordCount local[2] localhost 9999
And if I run nc -L -p 9999 in another terminal, then I can type letters in this terminal, and the example can receive the letters and give the right result.
But I developed a Java socket client to send content to 9999 port - why can't the example receive it? I think the example just monitor the 9999 port, and receive anything from the port.
Here is the Java code:
File file = new File("D:\\OutputJson.dat");
long l = file.length();
socket = new Socket();
boolean connected = false;
while (!connected) {
//not stop until send successful
try {
socket.connect(new InetSocketAddress("localhost", 9999));
connected = true;
System.out.println("connected success!");
} catch (Exception e) {
e.printStackTrace();
System.out.println("connected failed!");
Thread.sleep(5000);
}
}
dos = new DataOutputStream(socket.getOutputStream());
fis = new FileInputStream(file);
sendBytes = new byte[1024];
while ((length = fis.read(sendBytes, 0, sendBytes.length)) > 0) {
sumL += length;
System.out.println("sent:" + ((sumL / l) * 100) + "%");
dos.write(sendBytes, 0, length);
dos.flush();
}
if (sumL == l) {
bool = true;
}
This Java function is always returning the following error:
java.net.SocketException: Socket closed
I have developed another Java class to receive the data from this sending socket, and it works fine, why the can't spark receive with this one?

From memory I think I used a ServerSocket. The code was something like:
public void sendMsg(String msg) throws IOException {
ServerSocket serverSocket = null;
Socket clientSocket = null;
try {
serverSocket = new ServerSocket(port);
clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
out.write(msg);
out.flush();
out.close();
} finally {
try {
clientSocket.close();
serverSocket.close();
} finally {
clientSocket = null;
serverSocket = null;
}
}
}

Related

How can I send EOF signal to server ,when I use spring integration as tcp client?

I want use spring integration to replace socket client.My socket client code is like this:
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 7779);
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os);
String str = "hello server!";
pw.write(str);
pw.flush();
socket.shutdownOutput();
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String info = br.readLine();
while (info != null) {
System.out.println("i am client. server says that " + info);
info = br.readLine();
pw.close();
}
br.close();
is.close();
pw.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
socket client will get server's reply msg.
and I use spring integration to do the same job.
spring integration's xml code is like this:
<int:gateway id="gw"
service-interface="org.springframework.integration.samples.tcpclientserver.SimpleGateway"
default-request-channel="input"/>
<int-ip:tcp-connection-factory id="client"
type="client"
host="localhost"
port="7779"
single-use="true"
so-timeout="10000"/>
<int:channel id="input"/>
<int-ip:tcp-outbound-gateway id="outGateway"
request-channel="input"
reply-channel="clientBytes2StringChannel"
connection-factory="client"
request-timeout="10000"
reply-timeout="10000"/>
<int:object-to-string-transformer id="clientBytes2String"
input-channel="clientBytes2StringChannel"/>
it's a part of spring integration's tcp-client-server example https://github.com/spring-projects/spring-integration-samples/tree/master/basic/tcp-client-server
java code is like this:
final Scanner scanner = new Scanner(System.in);
final GenericXmlApplicationContext context = Main.setupContext();
final SimpleGateway gateway = context.getBean(SimpleGateway.class);
final AbstractServerConnectionFactory crLfServer = context.getBean(AbstractServerConnectionFactory.class);
TestingUtilities.waitListening(crLfServer, 10000L);
while (true) {
final String input = scanner.nextLine();
if ("q".equals(input.trim())) {
break;
}
else {
final String result = gateway.send(input);
System.out.println(result);
}
}
System.out.println("Exiting application...bye.");
System.exit(0);
}
public static GenericXmlApplicationContext setupContext() {
final GenericXmlApplicationContext context = new GenericXmlApplicationContext();
if (System.getProperty(AVAILABLE_SERVER_SOCKET) == null) {
System.out.print("Detect open server socket...");
int availableServerSocket = SocketUtils.findAvailableTcpPort(5678);
final Map<String, Object> sockets = new HashMap<>();
sockets.put(AVAILABLE_SERVER_SOCKET, availableServerSocket);
final MapPropertySource propertySource = new MapPropertySource("sockets", sockets);
context.getEnvironment().getPropertySources().addLast(propertySource);
}
System.out.println("using port " + context.getEnvironment().getProperty(AVAILABLE_SERVER_SOCKET));
context.load("classpath:META-INF/spring/integration/tcpClientServerDemo-context.xml");
context.registerShutdownHook();
context.refresh();
return context;
}
and I can't get sever reply, because server doesn't get a eof signal and it still blocked in readLine();
the exception I get :
org.springframework.integration.MessageTimeoutException: Timed out waiting for response.
Here is server code:
try {
ServerSocket serverSocket = new ServerSocket(7779);
Socket socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String info = br.readLine();
System.out.println("from client : "+info);
while (info != null) {
System.out.println("i am server. message from client is " + info);
info = br.readLine(); //server blocked here
}
socket.shutdownInput();
OutputStream os = socket.getOutputStream();
String replyMsg="welcom from server 7779 ACK\r\n";
os.write(replyMsg.getBytes());
os.close();
br.close();
isr.close();
is.close();
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
so how can I send a eof singal to server so my application will get the server's reply?
Spring Integration currently doesn't support those shutDown*() methods.
Please open a GitHub Issue and we'll take a look.

ReceiveAsync from UDP socket

I want to create a UDP socket to receive data from Local Endpoint.
I do not know the Remote Port where data come from, that's why I thought I would use ReceiveAsync. But it does not work.
I give my code right now and any advice would be useful:
public class Program
{
ManualResetEvent clientDone;
Socket socket;
public static void Main(string[] args)
{
clientDone = new ManualResetEvent(false);
socket = new Socket( AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint localIPEP = new IPEndPoint( IPAddress.Any, 0);
socket.Bind( (EndPoint) localIPEP);
while (listening)
Receive();
}
string Receive()
{
string response;
byte[] recvData = new byte[24];
if (socket != null)
{
SocketAsyncEventArgs ae = new SocketAsyncEventArgs();
ae.SetBuffer(recvData, 0, recvData.Length);
// callback
ae.Completed += new EventHandler<SocketAsyncEventArgs>(delegate (object s, SocketAsyncEventArgs e)
{
if (e.SocketError == SocketError.Success)
{
response = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);
response.Trim('\0');
}
else
{
response = e.SocketError.ToString();
}
switch (e.LastOperation)
{
case SocketAsyncOperation.Receive:
ProcessReceivedData(e);
break;
}
clientDone.Set();
});
clientDone.Reset();
Console.WriteLine("Local EndPoint: " + ((IPEndPoint)socket.LocalEndPoint).ToString());
socket.ReceiveAsync(ae);
clientDone.WaitOne(1000);
}
return response;
}
}
P.S. I work on Linux .Net Core

JSCH print System.err message on textview

I have solved this:
My solution:
I print ErrStream into 'in2' and then print it out just like 'in'
InputStream in2 = ((ChannelExec) channel).getErrStream();
My goal:
-To print Error message "bash: dumper: command not found" (as shown on android monitor) from System.err on textview
My Question:
-How can I read the Error message from System.err?
What is the code for:
-get ssh commands from user then display as what is it return
public void ssh_send_cmd(String input_cmd) {
ssh_input_cmd = input_cmd;
Runnable runnable = new Runnable() {
public void run() {
IDList.clear();
Connection connection = null;
Session session= null;
try {
JSch jsch = new JSch();
// Get SSH session
session = jsch.getSession(Global.servUser, Global.host, Global.port);
session.setPassword(Global.servPwd);
java.util.Properties config = new java.util.Properties();
// Never automatically add new host keys to the host file
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
// Connect to remote server
session.connect();
System.out.println("Connection through ssh established!");
String command = ssh_input_cmd;
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
((ChannelExec) channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
System.out.println("Connect to session...");
channel.connect();
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0) {
break;
}
System.out.print(new String(tmp, 0, i));
update_monitor(new String(tmp, 0, i));
}
if (channel.isClosed()) {
System.out.println("exit-status: " + channel.getExitStatus());
update_monitor("exit-status: " + channel.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
System.out.println(ee);
}
}
channel.disconnect();
}catch (Exception e) {
System.out.println(e);
update_monitor("error 1");
}finally{
if(session !=null && session.isConnected()){
session.disconnect();
}
}
}
};
Thread mythread = new Thread(runnable);
mythread.start();
}
Android Monitor:
com.example.acer.ssh_cmd I/System.out: Connection through ssh established!
com.example.acer.ssh_cmd I/System.out: Connect to session...
com.example.acer.ssh_cmd W/System.err: bash: dumper: command not found
com.example.asus.ssh_cmd I/System.out: exit-status: 127
bash: dumper:command not found
For your information: "dumper" is input from user and the command is not found

Multithreaded Server using TCP in Java

I'm trying to implement a simple TCP connection between Client/Server. I made the Server multithreaded so that it can take either multiple requests (such as finding the sum, max, min of a string of numbers provided by the user) from a single client or accept multiple connections from different clients. I'm running both of them on my machine, but the server doesn't seem to push out an answer. Not sure what I'm doing wrong here --
public final class CalClient {
static final int PORT_NUMBER = 6789;
public static void main (String arg[]) throws Exception
{
String serverName;
#SuppressWarnings("unused")
String strListOfNumbers = null;
int menuIndex;
boolean exit = false;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter host name...");
System.out.print("> ");
serverName = inFromUser.readLine();
Socket clientSocket = new Socket(serverName, PORT_NUMBER);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
//outToServer.writeBytes(serverName + '\n');
System.out.println("");
System.out.println("Enter 1 to enter the list of numbers");
System.out.println("Enter 2 to perform Summation");
System.out.println("Enter 3 to calculate Maximum");
System.out.println("Enter 4 to calculate Minimum");
System.out.println("Enter 5 to Exit");
while (!exit) {
System.out.print(">");
menuIndex = Integer.parseInt(inFromUser.readLine());
if (menuIndex == 1) {
System.out.println("Please enter the numbers separated by commas.");
System.out.print(">");
strListOfNumbers = inFromUser.readLine();
outToServer.writeBytes("List" + strListOfNumbers);
//continue;
}
else if (menuIndex == 2) {
outToServer.writeBytes("SUM");
System.out.println(inFromServer.readLine());
}
else if (menuIndex == 3) {
outToServer.writeBytes("MAX");
System.out.println(inFromServer.readLine());
}
else if (menuIndex == 4) {
outToServer.writeBytes("MIN");
System.out.println(inFromServer.readLine());
}
else if (menuIndex == 5) {
outToServer.writeBytes("EXIT");
exit = true;
}
}
}
}
public final class CalServer
{
static final int PORT_NUMBER = 6789;
public static void main(String[] args) throws IOException
{
try {
ServerSocket welcomeSocket = new ServerSocket(PORT_NUMBER);
System.out.println("Listening");
while (true) {
Socket connectionSocket = welcomeSocket.accept();
if (connectionSocket != null) {
CalRequest request = new CalRequest(connectionSocket);
Thread thread = new Thread(request);
thread.start();
}
}
} catch (IOException ioe) {
System.out.println("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
}
}
final class CalRequest implements Runnable
{
Socket socket;
BufferedReader inFromClient;
DataOutputStream outToClient;
TreeSet<Integer> numbers = new TreeSet<Integer>();
int sum = 0;
public CalRequest(Socket socket)
{
this.socket = socket;
}
#Override
public void run()
{
try {
inFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
outToClient = new DataOutputStream(socket.getOutputStream());
while(inFromClient.readLine()!= null) {
processRequest(inFromClient.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void processRequest(String string) throws IOException
{
String strAction = string.substring(0,3);
if (strAction.equals("LIS")) {
String strNumbers = string.substring(5);
String[] strNumberArr;
strNumberArr = strNumbers.split(",");
// convert each element of the string array to type Integer and add it to a treeSet container.
for (int i=0; i<strNumberArr.length; i++)
numbers.add(new Integer(Integer.parseInt(strNumberArr[i])));
}
else if (strAction.equals("SUM")) {
#SuppressWarnings("rawtypes")
Iterator it = numbers.iterator();
int total = 0;
while (it.hasNext()) {
total += (Integer)(it.next());
}
}
else if (strAction.equals("MAX")) {
outToClient.writeBytes("The max is: " + Integer.toString(numbers.last()));
}
else if (strAction.equals("MIN")) {
outToClient.writeBytes("The max is: " + Integer.toString(numbers.first()));
}
}
}
Since you are using readLine(), I would guess that you actually need to send line terminators.
My experience with TCP socket communications uses ASCII data exclusively, and my code reflects that I believe. If that's the case for you, you may want to try this:
First, try instantiating your data streams like this:
socket = new Socket (Dest, Port);
toServer = new PrintWriter (socket.getOutputStream(), true);
fromServer = new BufferedReader (new InputStreamReader
(socket.getInputStream()), 8000);
The true at the end the printWriter constructor tells it to auto flush (lovely term) the buffer when you issue a println.
When you actually use the socket, use the following:
toServer.println (msg.trim());
resp = fromServer.readLine().trim();
I don't have to append the \n to the outgoing text myself, but this may be related to my specific situation (more on that below). The incoming data needs to have a \n at its end or readLine doesn't work. I assume there are ways you could read from the socket byte by byte, but also that the code would not be nearly so simple.
Unfortunately, the TCP server I'm communicating with is a C++ program so the way we ensure the \n is present in the incoming data isn't going to work for you (And may not be needed in the outgoing data).
Finally, if it helps, I built my code based on this web example:
http://content.gpwiki.org/index.php/Java:Tutorials:Simple_TCP_Networking
Edit: I found another code example that uses DataOutputStream... You may find it helpful, assuming you haven't already seen it.
http://systembash.com/content/a-simple-java-tcp-server-and-tcp-client/

How do I send a message to a bluetooth device?

Using the bluetooth API in j2me, I want to send a message to another mobile phone. I have been able to discover devices and services on the corresponding devices. I have also been able to connect to the services however when I try to send a message from the server to the client. The message is written but the client does not seem to receive it ..
public void startServer() throws IOException {
UUID uuid = new UUID("1101", false);
//Create the service url
String connectionString = "btspp://localhost:" + uuid + ";name=xyz";
//open server url
StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier) Connector.open(connectionString);
//Wait for client connection
System.out.println("\nServer Started. Waiting for clients to connect...");
StreamConnection connection = streamConnNotifier.acceptAndOpen();
RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
System.out.println("Remote device address: " + dev.getBluetoothAddress());
System.out.println("Remote device name: " + dev.getFriendlyName(true));
Survey.setTitle(dev.getFriendlyName(true));
//read string from spp client
try {
DataInputStream in = connection.openDataInputStream();
OutputStream writer=connection.openDataOutputStream();
String str="";
TextField textfield;
for (int i=0;i<questions.size();i++){
textfield = (TextField) questions.elementAt(i);
str += formatSurvey(textfield,i)+"&";
}
writer.write(str.getBytes(), 0, str.getBytes().length);
writer.flush();
System.out.println("Written to client "+str);
System.out.println("Reading "+in.readUTF());
try {
displaySurveyresults(str);
}
catch(Exception e){
System.out.println(e.getMessage());
}
streamConnNotifier.close();
}
catch(Exception e){
System.err.println(e.getMessage());
}
}
public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
switchDisplayable(null , getList1());
list1.append(servRecord.toString(), null);
System.out.println("Service discovered..."+servRecord.toString());
for (int i=0;i<servRecord.length;i++){
try {
System.out.println("Test1");
//StreamConnection con = (StreamConnection) Connector.open(servRecord[i].getConnectionURL(0 , false));
String connURL = servRecord[0].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
// Open connection
StreamConnection con = (StreamConnection) Connector.open(connURL);
System.out.println("Test2");
DataInputStream in = con.openDataInputStream();
System.out.println("Test3"+in.readUTF());
//con.openDataOutputStream().write(142);
System.out.println("Test4 "+in.available());
byte[] bte=new byte[in.available()];
System.out.println("Test5 "+bte.length);
in.read(bte);
System.out.println("Test6");
for (int l=0;l<bte.length;l++){
System.out.println(bte[i]);
System.out.println("Test7");
stringItem.setText(stringItem.getText()+1 + bte[i]);
}
OutputStream outStream=con.openOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(outStream);
writer.write("Vimal");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
have I erred somewhere bcause these are codes from the Net?
Try replacing new UUID("1101", false); with new UUID(0x1101);.

Resources