This question already has answers here:
fsockopen equivalent in JSP
(3 answers)
Closed 4 years ago.
I have a task. By socket, pass the variable output.
String hex = "1040014116";
StringBuilder output = new StringBuilder();
for (int i = 0; i < hex.length(); i+=2) {
String str = hex.substring(i, i+2);
output.append((char)Integer.parseInt(str, 16));
}
System.out.println(output);
output has the form "0x10.."
There is a web server he needs to transfer this data and in return receive others.
int serverPort = 2003;
String address = "xx.xx.xx.xx";
try {
InetAddress ipAddress = InetAddress.getByName(address);
System.out.println(" IP address " + address + " and port " + serverPort);
Socket socket = new Socket(ipAddress, serverPort);
System.out.println("Socket ready");
InputStream sin = socket.getInputStream();
OutputStream sout = socket.getOutputStream();
DataInputStream in = new DataInputStream(sin);
DataOutputStream out = new DataOutputStream(sout);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line = null;
System.out.println("Введите данные и нажмите 'Ввод'");
System.out.println();
while (true) {
line = reader.readLine();
System.out.println("Отправка на сервер");
out.writeUTF(line);// отправка текста
System.out.println("Отправка: : " + line);
out.flush(); // конец передачи
line = in.readUTF(); // возврат текста от сервера
System.out.println("Сервер: : " + line);
System.out.println("Введите новую строку");
System.out.println();
}
} catch (Exception x) {
x.printStackTrace();
}
}
How to pass a bit string and get a bit string from the server in response.
U need to code on both client and server side
SERVER code
ServerSocket sskt=new ServerSocket(port);
Socket =sskt.accept()
InputStream is=skt.getInputStream();
OutputStream os=skt.getOutputStream();
ClIENT code
Socket skt=new Socket(server_ip,port);
Use same inputstream and outputstream to read and write once the connection has been established
Hope this helps
Related
I'm writing a java-c client-server, where the server is in C and the client is in Java. The socket is reused. I don't know why but the client reads the first response from the socket then loops, it's like the client isn't getting "\n". What am I not getting?
The C server sends the response in the format (length:stringlength:string) etc
import java.io.*;
import java.net.*;
public class client {
public static void main(String[] args) {
if (args.length != 2) {
System.err.println("Use: java Client server port");
System.exit(1);
}
try{
BufferedReader fromUser = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Insert input1: ");
String input1 = fromUser.readLine();
System.out.println("Insert input2: ");
String input2 = fromUser.readLine();
Socket s = new Socket(args[0], Integer.parseInt(args[1]));
//BufferedReader fromServer = new BufferedReader(new InputStreamReader(s.getInputStream(),"UTF-8"));
InputStream is = s.getInputStream();
BufferedWriter toServer = new BufferedWriter(new OutputStreamWriter(s.getOutputStream(),"UTF-8"));
do {
String message = "(" + input1.getBytes("UTF-8").length + ":" + input1 + input2.getBytes("UTF-8").length + ":" + input2 + ")";
toServer.write(message);
toServer.flush();
/*reading result from server*/
//String buff;
String output = "";
byte[] buffer = new byte[4096];
int read;
while((read = is.read(buffer)) != -1) {
output = new String(buffer, 0, read);
System.out.print(output);
System.out.flush();
};
if(output.charAt(0) != '(' || output.charAt(output.length()-1) != ')'){
System.out.println("error using protocol");
}
if(output.indexOf(':')<0){
System.err.println("error using Canonical S-expression!");
System.exit(2);
}
for(int i=output.indexOf(":")+1;i<output.length()-2;i++){
System.out.print(output.charAt(i));
}
System.out.println();
s.close();
System.out.println("Insert input1: ('end' to exit)");
input1 = fromUser.readLine();
} while(!input1.equals("end"));
}
catch(IOException e){
System.err.println(e.getMessage());
e.printStackTrace();
System.exit(100);
}
}
}
In example below I created one server which will only print whatever client is writing in a socket. But I am not getting output as client enter data. If client terminate then I can see all the data client inserted in outputstream. I am taking input from console at client and then write that data to server socket.
Server code:
public class server {
public static void main(String[] args) throws Exception {
System.out.println("waiting");
ServerSocket s = new ServerSocket(9999);
Socket stemp = s.accept();
System.out.println("read comp");
InputStream is = stemp.getInputStream();
InputStreamReader ir = new InputStreamReader(is);
BufferedReader br = new BufferedReader(ir);
while(true)
{
String str = br.readLine();
if(str!=null)
{
System.out.println(str);
}
if(str.contains("exit"))
{
break;
}
}
stemp.close();
ir.close();
is.close();
br.close();
}
}
Client code:
public class client {
public static void main(String[] args) throws Exception {
String ip ="127.0.0.1";
int port = 9999;
Socket s1 = new Socket(ip, port);
OutputStream os = s1.getOutputStream();
OutputStreamWriter ow = new OutputStreamWriter(os);
BufferedWriter pw = new BufferedWriter(ow);
pw.write("I am ready");
Scanner s = new Scanner(System.in);
String str = s.nextLine();
System.out.println(str);
while(!str.contains("exit"))
{
pw.write(str);
pw.flush();
str = s.nextLine();
}
pw.close();
os.close();
ow.close();
s1.close();
}
}
In server, br.readLine(); is used, waiting for end-of-line.
In client, you have to send the eol in pw.write( str + '\n' );.
My partner system services socket server. They don't share the client module, only test sample data.
First, I tested using telnet program and it's successful.
this image link is the test using telnet program.
But my Java socket client can't receive message from socket server.
this image link is result of my socket program.
Would you help me?
Thanks.
public static void main(String[] args) {
System.out.println("file.encoding: " + System.getProperty("file.encoding"));
try {
Socket socket;
final String HOST = "xx.xx.xx.xxx"; // partner test server
final int PORT = 8994;
try {
socket = new Socket(HOST, PORT);
} catch (IOException ioe) {
System.out.println(">>>");
System.out.println(ioe.getMessage());
System.out.println(">>>");
throw ioe;
}
System.out.println("sending data:");
OutputStream os = socket.getOutputStream();
byte[] b = "xxxx52017082410332310000000020321 ONL00000 080081COP0045 3xxxxxxxxxxxxxxx/jOsBUe5I11C2mtP0j5tPSww==20170824103323 ".getBytes();
for (int i = 0; i < b.length; i++) {
os.write(b[i]);
}
os.flush();
socket.shutdownOutput();
System.out.println(new String(b) + "[END]");
System.out.println("receiving data");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
socket.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
I found the solution.
The sever socket program sent byte data, not string line.
Please find below my source code.
Thanks everyone.
socket = new Socket(ip, port);
System.out.println("SEND DATA[" +msg.length() + "] [" + msg + "]");
oout = new BufferedOutputStream(socket.getOutputStream());
iin = new BufferedInputStream(socket.getInputStream());
oout.write(msg.getBytes());
oout.flush();
byte[] buffer = new byte[1156];
System.out.println("RECV DATA");
iin.read(buffer);
System.out.println("RECV DATA [" + new String(buffer) +"]");
I'm trying to learn how to do deal with networks in Java 8, and I'm trying to make a client program communicate with a server one. The client is asked a string, which is sent to the server, and the server sends it back in upper characters.
I can't get my server part to work, it simply won't write anything except the fact that the connection is made. Could someone explain what's wrong with my code ?
Server :
public static void main(String[] args) throws IOException {
int listenPort = 9000;
ServerSocket listenSocket = new ServerSocket(listenPort);
Socket socket = listenSocket.accept();
System.out.println("Connexion réussie !");
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
BufferedReader buffer = new BufferedReader(new InputStreamReader(inputStream));
DataOutputStream output = new DataOutputStream(outputStream);
String line = null;
System.out.println("test : " + buffer.readLine());
while((line = buffer.readLine()) != null) {
System.out.println("Message reçu : " + line);
System.out.println("Message envoyé : " + line.toUpperCase());
output.writeUTF(line.toUpperCase());
if(line.equals("stop")) {
socket.close();
listenSocket.close();
}
}
}
Client side :
public static void main(String[] args) throws IOException, UnknownHostException {
Socket socket = new Socket("127.0.0.1", 9000);
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
DataInputStream input = new DataInputStream(inputStream);
DataOutputStream output = new DataOutputStream(outputStream);
BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while((line = buffer.readLine()) != null) {
System.out.println("Message envoyé : " + line);
output.writeChars(line);
System.out.println("Message reçu : " + input.readUTF());
if(line.equals("stop")) {
break;
}
}
socket.close();
}
Inside your client method, you call output.writeChars(line) inside the while loop, this means that you send something to the server after the server send something to you.
Change your client code as follows:
String line = "What a wonderful line";
System.out.println("Message envoyé : " + line);
output.writeChars(line);
while((line = buffer.readLine()) != null) {
System.out.println("Message reçu : " + input.readUTF());
}
I'm creating a simple client-server to use with my Raspberry Pi.
What I'm trying to accomplish is to send "ACKTEMP" for example to the Server using my Client. The servers then calls the serial port (which is my STM32 Nucleo Board btw) with this message I get the temperature back using the serial communication and after that it sends it back to the Client.
My question is, the Nucleo board returns some strings like (TEMP: xx) this works fine until I start sending multiple strings back at once ex. if I send ACKTEMP and want to receive (TEMP: xx ) and "Temperature OK", doing this I only get the first line which is (TEMP: xx ).
So it seems that somewhere in my code I need to change something so it prints out all the lines instead of just one and then stop. Please don't get angry at me if my programming isn't that great I'm a student and trying to understand everything.
public class Client {
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
String sentence;
String messageFromServer;
while(true)
{
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
try (Socket clientSocket = new Socket("192.168.0.135", 6789)) {
PrintWriter outToServer = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.println(sentence + '\n');
messageFromServer = inFromServer.readLine();
System.out.println("FROM SERVER: " + messageFromServer);
clientSocket.close();
}
}
}
}
public class Server {
private static SerialPort serialPort;
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
serialPort = new SerialPort("/dev/ttyACM0");
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
PrintWriter outToClient = new PrintWriter(connectionSocket.getOutputStream(), true);
clientSentence = inFromClient.readLine();
try{
//opening port
serialPort.openPort();
serialPort.setParams(
SerialPort.BAUDRATE_115200,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
//Write string to port
serialPort.writeString(clientSentence + "\n");
System.out.println("String wrote to port, waiting for response..");
try {
Thread.sleep(10); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
String buffer = serialPort.readString();
outToClient.println(buffer + '\n');
serialPort.closePort();//Close serial port
}
catch(SerialPortException ex){
System.out.println("Error writing data to port: " + ex);
}
}
// TODO code application logic here
}
}
I used the following to kinda solve this problem. But if someone has a better solution it is very welcome!
What I did is for every string I want a new line, I put a "~" sign in front of the string in my Nucleo STM32 program.
String strArray[] = messageFromServer.split("~");
System.out.println("FROM SERVER: " + strArray[0]);
for(int i = 1; i < strArray.length; ++i)
{
if(messageFromServer.indexOf('~') >= 0)
{
System.out.println("FROM SERVER: " + strArray[i]);
}
}