I am trying to create a socket connection and then passing the values from the file to the socket as a stream.
I did managed to pass data to socket from the PrintStream,
socketInput= "1234,112,1121"
val ss = new ServerSocket(4141)
val sock = ss.accept()
val is = new BufferedInputStream(sock.getInputStream)
val os =new PrintStream(new BufferedOutputStream(sock.getOutputStream))
os.println(socketInput)
os.flush()
sock.close()
Now rather than providing the input to socket directly from Print stream I need to provide it from the csv file.
And while I was reading about the FileOutputStream it is used to write data to file.
How, Can we read from the file instead and pass to the socket.
If your question is how to read content of a file and sending and receiving it through sockets, you can use these samples. First of all, You should run Server.java, after that please change path and name of file in Client.java and finally run client.
Server.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String args[]) {
System.out.println("Server is ready:");
int SERVER_PORT = 7005;
ServerSocket serverSocket = null;
Socket conn = null;
try {
serverSocket = new ServerSocket(SERVER_PORT, 50);
while (true) {
conn = serverSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
if(line.indexOf("END") > -1) {
in.close();
break;
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client.java
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
public class Client {
public static void main(String[] args) {
int SERVER_PORT = 7005;
try {
Socket conn = new Socket("localhost",SERVER_PORT);
PrintWriter out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream()));
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("/home/mohammadmehdi/development/eclipse/neonWorkSpace/javaTest/SocketTest/src/temp.txt"), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
out.println(line);
out.flush();
}
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Related
I am using the below mentioned code to commit a file to github.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class GitHubRestClient {
public static void main(String[] args) {
try {
URL url = new URL("https://api.github.com/repos/userid/test/contents/test/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("PUT");
conn.setRequestProperty("Accept", "application/vnd.github+json");
conn.setRequestProperty("Authorization", "Bearer ");
conn.setRequestProperty("X-GitHub-Api-Version", "2022-11-28");
conn.setRequestProperty("User-Agent", "Request");
String input = "{\"message\":\"my commit message\",\"committer\":{\"name\":\"Nithin\",\"email\":\"nithin#mail.com\"},\"content\":\"bXkgbmV3IGZpbGUgY29udGVudHM=\"}";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseMessage());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I am getting ** 422 HTTP error code: Unprocessable Entity** error.
Using the same values in the curl command I was able to upload the files
I'm writing a simple tcp server for short connection.
I have two vertical.
One handling the tcp request, get the eventBus and send the message to it.
Another vertical just consume and reply it.
The question is.Tcp client can't receive the result.I know the eventBus.request() is async.But don't know how to control it,just let the socket waiting for the result.
main
package org.example;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
public class Application {
public static void main(String[] args) {
VertxOptions options = new VertxOptions();
options.setEventLoopPoolSize(1);
Vertx vertx = Vertx.vertx(options);
DeploymentOptions ruleOptions = new DeploymentOptions();
ruleOptions.setWorker(true);
ruleOptions.setInstances(1);
vertx.deployVerticle("org.example.RuleVertical", ruleOptions);
DeploymentOptions serverOptions = new DeploymentOptions();
serverOptions.setInstances(1);
vertx.deployVerticle("org.example.ServerVertical", serverOptions);
}
}
server vertical
package org.example;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.net.NetServer;
public class ServerVertical extends AbstractVerticle {
#Override
public void start() throws Exception {
EventBus eventBus = vertx.eventBus();
NetServer netServer = vertx.createNetServer();
netServer.connectHandler(socket -> {
socket.handler(buffer -> {
eventBus.request("message.id", buffer.toString(), reply -> {
System.out.println("Server reply: " + reply.result().body());
socket.write(reply.result().body().toString()).onFailure(event -> event.printStackTrace());
});
});
});
netServer.listen(1234);
}
}
rule vertical
package org.example;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.eventbus.EventBus;
public class RuleVertical extends AbstractVerticle {
#Override
public void start() throws Exception {
EventBus eventBus = vertx.eventBus();
eventBus.consumer("message.id", message -> {
try {
Thread.sleep(2000);
message.reply("hello");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
}
client
package org.example;
import java.io.*;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1", 1234);
OutputStream outputStream = socket.getOutputStream();
PrintWriter printWriter = new PrintWriter(outputStream);
System.out.println("Request: 1234");
printWriter.write("1234");
printWriter.flush();
socket.shutdownOutput();
InputStream inputStream = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
System.out.println("Response: " + sb);
reader.close();
printWriter.close();
inputStream.close();
outputStream.close();
socket.close();
}
}
Server log
Server reply: hello
io.netty.channel.StacklessClosedChannelException
at io.netty.channel.AbstractChannel$AbstractUnsafe.write(Object, ChannelPromise)(Unknown Source)
Client log
Request: 1234
Response:
I tried using s_client (openssl) and the javax.net.ssl package to connect to encrypted socket.
s_client works but probably not on non-rooted android, that is why i tried the javax.net.ssl package but i get the following error:
java.net.SocketException: Socket has been closed or broken
Also, what is "NaiveTrustManager()"? (https://github.com/maruohon/JavaIRC)
package SSLSocketClient;
import java.io.*;
import java.net.*;
import javax.net.ssl.*;
public class SSLSocketClient{
public static void main(String[] args) {
SSLSocketFactory f =
(SSLSocketFactory)SSLSocketFactory.getDefault();
try {
SSLSocket s =
(SSLSocket) f.createSocket("localhost", 6697);
s.startHandshake();
BufferedReader reader = new BufferedReader (new
InputStreamReader(s.getInputStream()));
BufferedWriter writer = new BufferedWriter(new
OutputStreamWriter(s.getOutputStream()));
BufferedReader in = new BufferedReader(
new InputStreamReader(
s.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
s.close();
} catch (IOException e) {
System.err.println(e.toString());
}
}
I solved it by Accepting Self-Signed SSL Certificates in Java..
http://howardism.org/Technical/Java/SelfSignedCerts.html
I am trying to relay a message from a Servlet to COM in raspberry pi on Tomcat 7.
I am using null cable between raspberry and my PCs to test.
I am using jssc API (Java Simple Serial Connector) for serial communication.
Raspberry pi is using JDK 1.8.0_65.
I am getting the message in UTF8 and I should output it in ISO8859-7.
Since UTF8 is a superset of ISO8859-7, the app that calls the servlet ensures all characters sent are legitimate for ISO8859-7.
My code:
package com.test.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import jssc.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(value = "/Relay", name = "Relay")
public class Relay extends HttpServlet {
static Logger app = null;
static {
app = Logger.getLogger("com.test.app");
}
protected void doGet(HttpServletRequest request,HttpServletResponse response) {
doPost(request, response);
}
protected void doPost(HttpServletRequest request,HttpServletResponse response) {
try {
request.setCharacterEncoding("ISO-8859-7");;
response.setCharacterEncoding("ISO-8859-7");
//request.setCharacterEncoding("UTF-8");
//response.setCharacterEncoding("UTF-8")
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String message = request.getParameter("message");
app.logp(Level.INFO, this.getClass().getCanonicalName(),"APP", message);
String[] portNames = SerialPortList.getPortNames();
app.logp(Level.INFO, this.getClass().getCanonicalName(),"APP", portNames.length+"");
for(int i = 0; i < portNames.length; i++){
applogp(Level.INFO, this.getClass().getCanonicalName(),"APP", portNames[i]);
byte[] msg = new byte[1024];
msg = message.getBytes("ISO-8859-7");
Charset utf8charset = Charset.forName("UTF-8");
Charset iso88597charset = Charset.forName("ISO-8859-7");
ByteBuffer inputBuffer = ByteBuffer.wrap(message.getBytes());
CharBuffer data = utf8charset.decode(inputBuffer);
ByteBuffer outputBuffer = iso88597charset.encode(data);
byte[] outputData = outputBuffer.array();
byte[] b1 = message.getBytes();
byte[] b2 = message.getBytes(Charset.forName("ISO-8859-7"));
byte[] b3 = message.getBytes(StandardCharsets.ISO_8859_1);
SerialPort serialPort = new SerialPort((portNames[i]));
try {
serialPort.openPort();
serialPort.setParams(SerialPort.BAUDRATE_9600,SerialPort.DATABITS_8, SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
serialPort.writeBytes(msg);
serialPort.writeBytes(message.getBytes());
serialPort.writeBytes(outputData);
serialPort.writeBytes(b1);
serialPort.writeBytes(b2);
serialPort.writeBytes(b3);
serialPort.closePort();
} catch (SerialPortException ex) {
app.logp(Level.INFO, this.getClass().getCanonicalName(),"APP", ex.getMessage());
out.write("NOK");
out.close();
}
}
out.write("OK");
out.close();
} catch (IOException e) {
app.logp(Level.INFO, this.getClass().getCanonicalName(),"APP", e.getMessage());
}
}
private static final long serialVersionUID = 1L;
}
The problem is that when I am testing I do not get valid output in putty.
putty output
I have configured putty to display ISO8859-7 characters.
Any for changes ?
What am I missing ?
Thanks in advance.
I tried to divide the problem by producing the following code:
import java.io.UnsupportedEncodingException;
import jssc.SerialPort;
import jssc.SerialPortException;
public class SerialTest {
public static void main(String[] args) {
String message = "message μήνυμα";
if ( sendTextOnCom(message) ) {
System.out.println("SUCCESS MESSAGE SENT");
}
else{
System.out.println("FAIL MESSAGE NOT SENT");
}
}
private static boolean sendTextOnCom(String message) {
boolean isOverlaid = false;
SerialPort com = null;
try {
String comNo = "COM1"; // String comNo="/dev/ttyUSB0"; //when used in Raspberry
com = new SerialPort(comNo);
com.openPort();
com.setParams(9600, 8, 1, 0);
com.writeString(message);
com.writeBytes(message.getBytes("ISO-8859-7"));
com.closePort();
isOverlaid = true;
}
catch (SerialPortException ex) {
System.out.println("[ERROR] COM ERROR SENDING MESSAGE");
isOverlaid = false;
try {
com.closePort();
} catch (SerialPortException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return isOverlaid;
}
}
The code is working normally in Windows 7 64bit and it is producing output in putty with the right characters.
When I compile and run the same code in raspberry PI the output in putty is not showing the valid characters.
I tend to think that it's a raspberry PI configuration issue.
I have set up a network and I've set up the reading and writing stream to a socket as so:
//Set up socket reads and writes
final BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream()));
final PrintWriter out = new PrintWriter(
client.getOutputStream(), true);
I wanted to pass the two variables, 'in' and 'out', as parameters of another class' constructor. This is how it looks in the other class
BufferedReader in;
PrintWriter out;
public ClientThread(BufferedReader in, PrintWriter out) {
this.in = in;
this.out = out;
}
I then wanted to use those class variables to write to the output stream of the same socket like this (the class implements Runnable):
public void run() {
while (true) {
try {
String userCommand = in.readLine();
} catch (IOException e) {
// Die if something goes wrong.
System.err.println(e.toString());
System.exit(1);
}
}
}
However, whenever the code gets to this point, I get a SocketException:
java.net.SocketException: Socket closed
How can I fix this? I want to separate the setting up of the server and the socket from the processing of any commands given by the client.
EDIT: Here's what the BufferedRead gets the input from
//create server socket
ServerSocket server = new ServerSocket(portNum);
// Accept a client if it appears
Socket client = server.accept();
EDIT 2: I used these three files:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException {
//Change the socket if it doesn't work
Socket sock = new Socket("localhost", 5920);
//keyboard
final BufferedReader stdin = new BufferedReader(
new InputStreamReader(System.in));
//input from socket
final BufferedReader in = new BufferedReader(
new InputStreamReader(sock.getInputStream()));
//writer to socket
final PrintWriter out = new PrintWriter(
sock.getOutputStream(), true);
//new thread for incoming messages
(new Thread(){
#Override
public void run() {
String serverMessage;
try {
while ((serverMessage = in.readLine()) != null) {
System.out.println(serverMessage);
}
} catch (IOException e) {
System.err.println("Something went wrong whilst trying "
+ "to retrieve a message from the server");
System.exit(-1);
}
}
}).start();
//new thread for outgoing messages
(new Thread(){
#Override
public void run() {
String clientMessage;
try {
while ((clientMessage = stdin.readLine()) != null) {
out.println(clientMessage);
}
} catch (IOException e) {
System.err.println("Something went wrong whilst trying "
+ "to send a message to the server.");
System.exit(-1);
}
}
}).start();
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(5920);
Socket client = server.accept();
//Set up socket reads and writes
final BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream()));
final PrintWriter out = new PrintWriter(
client.getOutputStream(), true);
new Thread(new ClassWithParam(in, out)).start();
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
public class ClassWithParam implements Runnable {
BufferedReader in;
PrintWriter out;
public ClassWithParam(BufferedReader in, PrintWriter out) {
this.in = in;
this.out = out;
}
#Override
public void run() {
while (true) {
try {
System.out.println("HERE");
String userCommand = in.readLine();
System.out.println("HERE2");
} catch (IOException e) {
// Die if something goes wrong.
System.err.println(e.toString());
System.exit(1);
}
}
}
}
And now it works. Don't know what happened. Will proceed to bang head against wall. Thanks.
For some reason there's no problem now. The code (I recreated) which I used, which now works, is in the description.