I'm trying to send data from Labview over a TCP socket and receiving the data with Java.
I'm using an example TCP VI from Labview (I cant post pictures).
I realize there's a TCP read, I haven't gotten to that point yet. My problem is dealing with types.
import java.io.*;
import java.net.*;
public class JavaApplication3 {
public static void main(String[] args) throws IOException {
String serverHostname = new String ("97.77.53.127");
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket(serverHostname, 6340);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.exit(1);
} catch (IOException e) {
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
System.out.print ("input: ");
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
System.out.print ("input: ");
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
My first problem I want to deal with, is whenever I receive a input from the Labview VI, in the java program I get:
input: d
echo: ?��/�?�~gʕ ?�$���;P?��G��j�?��"�?�?��;���h?�
input: input: d
echo: ?��/�?�~gʕ ?�$���;P?��G��j�?��"�?�?��;���h?�
input:
I'm assuming my problem is with type casting, but I really don't know enough to fix it.
Any help would be appreciated.
Ok, then try something like:
int temp = 0;
while( (temp = in.read()) != -1){
System.out.print( (char)temp );
}
Just put this somewhere in your code. This simply casts the int returned to a char value, which will print out the letters.
Let me know how it goes.
Related
I'm new to socket. I want to make a client-server program but I have a problem when it comes to printing messages on the side of the server. That leads me to believe there is a problem in my Client class when it is sending the messages. The first message that is sent from client to server is delivered fine but the rest aren't printed even though the sequence number is printed.
Here are both classes:
Client class:
public class Cliente extends Conexion {
private String mensaje;
private String recibeTeclado;
int numSec = 0;
String tipo = "0";
private int num;
int c;
public Cliente() throws IOException{
super("cliente");
}
public void startClient() {
try {
salidaServidor = new DataOutputStream(cs.getOutputStream());
Scanner lee = new Scanner(System.in);
System.out.println("How many messages do you want to send?");
num = lee.nextInt();
salidaServidor.writeUTF(":" + num + "\n");
for (int i = 1; i <= num; i++) {
numSec++;
System.out.println("Enter the message: ");
recibeTeclado = lee.next();
mensaje = tipo + ":" + Integer.toString(numSec) + ":" + recibeTeclado + "\n";
salidaServidor.writeUTF(mensaje);
salidaServidor.flush();
BufferedReader in = new BufferedReader (new InputStreamReader (cs.getInputStream()));
String mensajeDelServidor = in.readLine();
System.out.println("Status : " + mensajeDelServidor);
}
cs.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Server class:
public class Servidor extends Conexion{
String nuevo;
int numSec=0;
String tipo="1";
int num;
String [] n;
public Servidor() throws IOException{super("servidor");}
public void startServer() {
try {
System.out.println("Waiting...");
cs = ss.accept();
BufferedReader numString = new BufferedReader(new InputStreamReader(cs.getInputStream()));
n=numString.readLine().split(":");
num=Integer.parseInt(n[1]);
for(int i=1; i<=num; i++) {
salidaCliente=new DataOutputStream(cs.getOutputStream());
numSec++;
System.out.println(numSec);
nuevo= tipo +":"+ Integer.toString(numSec) +":"+ "Received\n";
salidaCliente.writeUTF(nuevo);
salidaCliente.flush();
BufferedReader entrada = new BufferedReader(new InputStreamReader(cs.getInputStream()));
boolean band=false;
while((mensajeServidor=entrada.readLine())!=null && !band) {
String[] arrSplit = mensajeServidor.split(":");
System.out.println(arrSplit[2]);
band=true;
}
}
System.out.println("Fin de la conexión");
ss.close();
cs.close();
}catch (Exception e)
{
System.out.println(e.getMessage());
}
}
}
[Updated, thanks to #user207421's comment]
2 solutions
Keep using DataOutputStream.writeUTF
Then you have to use DataInputStream.readUTF instead of BufferedReader.readLine.
And if you want to use '\n' as a separator, you will have to detect such characters
Keep using BufferedReader.readLine
Then you have to use an output stream method like Writer.write instead of DataOutputStream.writeUTF.
Use only one BufferedReader instance, on server side at least (numString will keep buffered data that will not be available for the entrada instance).
For UTF-8, use:
BufferedReader in = new BufferedReader(new InputStreamReader(cs.getInputStream(), "UTF-8"));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(cs.getOutputStream(), "UTF-8"));
On the client side, you should use a PrintWriter instead of a DataOutputStream to write data to the server:
salidaServidor = new PrintWriter(cs.getOutputStream(), true);
On the server side, 'salidaCliente' should also be a PrintWriter.
In the Java networking tutorial, we find the KnockKnock Client/Server pair. So I want to sit back and have the KnockKnockClient automatically send the clues to the server classes (which are KnockKnockServer/KnockKnockProtocol ). Here is what I tried :
import java.net.*;
import java.io.*;
import javax.swing.Timer;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class KnockKnockClientRedone {
static String KKJokes[] = { "Who's there?", "Turnip who?", "y", "Who's there?", "Little Old Lady who?", "y", "Who's there?", "Doctor who?", "y" };
public static void main(String[] args) throws IOException {
Socket kkSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
kkSocket = new Socket("localhost", 4444);
out = new PrintWriter(kkSocket.getOutputStream(), true);
for (int i = 0; i< KKJokes.length; i++) {
try {
Thread.sleep(1500); }
catch(Exception e){
e.printStackTrace();
}
in = new BufferedReader(
new InputStreamReader(
new ByteArrayInputStream(
KKJokes[i].getBytes()) ) );
}
} //try
catch ( IOException io ){
System.err.println("Calling IO . toString " + io.toString()); //System
System.exit(1);
}//catch
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromServer2;
String fromUser;
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("bye."))
break;
fromUser = stdIn.readLine();
if (fromUser != null){
System.out.println("Client: " + fromUser);
out.println(fromUser);
}
}
out.close();
in.close();
stdIn.close();
kkSocket.close();
}
}
But I noticed that something is wrong with my code here :
in = new BufferedReader(
new InputStreamReader(
new ByteArrayInputStream(
KKJokes[i].getBytes()) ) );
It only loops through til the end, and then in contains the last String in the String array. What I need is for the Client to send a String over the client, then proceed to the next String only when the Server sends back. Since I'm on a local machine, I thought that a delay of 1 second would be sufficient.
Any tips appreciated thanks
i have client server socket programming in java .
Server: Multi-threading server to serve the client for math calculations ,eg: sum of all numbers provided from client etc....
client: is to connect to the server and select specif math operations addition,subtraction ...
etc ,and provide the numbers to the server to return the result,and maybe the results is single value or maybe the result from server is array of numbers and depends on the type of the operation...
my Problem is: reading and writing blocking from server to client and vice-versa
eg:
**server->client :*** Welcome to the Calculation Server
server->client: "*** Please type in the num of rows: \n"
client->server: the user insert num of rows and send it to server
server->client: "*** Please type in the num of cols: \n"
client->server: the user insert num of columns and send it to server
server->client:writer.write("Enter the elements of first matrix");
client->server: at the client side it blocks or hang i dont know y???**
the server send
part of server code
import java.net.*;
import java.io.*;
class server_thread extends Thread
{
protected Socket clientSocket;
public static void main(String[] args) throws IOException
{
ServerSocket serverSocket = null;
int port=10008;
try {
serverSocket = new ServerSocket(port);
System.out.println ("Connection Socket Created on port : "+port);
try {
while (true)
{
System.out.println ("Waiting for Connection");
new server_thread (serverSocket.accept());
}
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
}
catch (IOException e)
{
System.err.println("Could not listen on port: 10008.");
System.exit(1);
}
finally
{
try {
serverSocket.close();
}
catch (IOException e)
{
System.err.println("Could not close port: 10008.");
System.exit(1);
}
}
}
private server_thread (Socket clientSoc)
{
clientSocket = clientSoc;
start();
}
public void run()
{
System.out.println ("New Communication Thread Started");
try {
BufferedReader reader =
new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
BufferedWriter writer=
new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
String sinput_row, sinput_col,srow_count, scol_count;
int row_count, col_count;
writer.write("*** Welcome to the Calculation Server ( ***\r\n");
////////////////////////////////////////////////////////////////////////////////////////////////
writer.write("*** Please type in the num of rows: \n");
writer.flush();
sinput_row = reader.readLine().trim();
int input_row=Integer.parseInt(sinput_row);
System.out.println("num of rows got:"+input_row);
//////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
writer.write("*** Please type in the num of cols: \n");
writer.flush();
sinput_col = reader.readLine().trim();
int input_col=Integer.parseInt(sinput_col);
System.out.println("num of Cols got:"+input_col);
//////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
writer.write("Enter the elements of first matrix");
writer.flush();
int first[][] = new int[input_row][input_col];
int second[][] = new int[input_row][input_col];
int sum[][] = new int[input_row][input_col];
for ( row_count = 0 ; row_count < input_row ; row_count++ )
for ( col_count = 0 ; col_count < input_col ; col_count++ )
{
String s_matrix1_element=reader.readLine().trim();
int matrix1_element=Integer.parseInt(s_matrix1_element);
first[row_count][col_count] = matrix1_element;
}
// the rest of code is ommited for simplicty of analysis
////////////////////////////////////////////////////////////////////////////////////////////////
//int result=num1+num2;
System.out.println("Addition operation done " );
writer.flush();
writer.write("");
//writer.write("\r\n=== Result is : "+result);
writer.flush();
clientSocket.close();
}
catch (IOException e)
{
System.err.println("Problem with Communication Server");
System.exit(1);
}
}
}
and here is client code :
import java.io.*;
import java.net.*;
import java.util.*;
public class client_thread {
public static void main(String argv[])
{
try{
Socket socketClient= new Socket("localhost",10008);
System.out.println("Client: "+"Connection Established");
BufferedReader reader =
new BufferedReader(new InputStreamReader(socketClient.getInputStream()));
BufferedWriter writer=
new BufferedWriter(new OutputStreamWriter(socketClient.getOutputStream()));
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String serverMsg;
String userInput;
writer.flush();
serverMsg = reader.readLine();
System.out.println("from server: " + serverMsg);
while((serverMsg = reader.readLine()) != null )
{
System.out.println("from server inside loop: " + serverMsg);
userInput = stdIn.readLine();
writer.write(userInput+"\r\n");
writer.flush();
}
}catch(Exception e){e.printStackTrace();}
}
}
so the problem
Your server writes:
writer.write("Enter the elements of first matrix");
And the client reads this using
while((serverMsg = reader.readLine()) != null)
So, since the server doesn't send any end of line, the clients waits for it.
Method 1:
Use 1 thread to handle your input stream and another thread to handle your output stream. Then you can do you read and write concurrently.
Method 2:
Use NIO (Non Blocking I/O).
I have a client server architecture in Java in which I need to place a loop.
I've spent some time to think about where to put this loop, but anywhere I tried it did not get the result expected.
Here is my client.java :
public class Client {
private static Scanner scanner;
public static void main(String[] args) throws IOException {
scanner = new Scanner(System.in);
// set up server communication
Socket clientSocket = new Socket(InetAddress.getLocalHost(), 1234);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream());
System.out.println("Enter pin : ");
String password = scanner.next();
// send PIN to server
out.println(password);
out.flush();
// get response from server
String response = in.readLine();
System.out.println(response);
scanner.close();
in.close();
out.close();
clientSocket.close();
}
}
Here is my server.java :
public class Server {
private static ServerSocket server;
public static void main(String[] args) throws Exception {
server = new ServerSocket(1234);
Socket socket = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream());
// Listen for client requests:
String request = in.readLine();
while (request != null) {
// check PIN, send result
boolean pinCorrect = checkPin(request);
out.println(pinCorrect ? ":)" : ":(");
out.flush();
}
out.close();
in.close();
socket.close();
}
}
I need to repeat this process if the user does not enter exactly 4 digits, so I've been thinking of a do{}while(pinSize != 4) loop.
But when I place it in the Server I always have the wrong output ":)" or ":(" instead of just "Pin must be 4 digits", then I tried to put in the Client part, but this time I always had the possibility to enter only one pin so the loop did not work that much.
Actually this is some code I would put into my loop:
if (pinSize != 4) {
System.out.println("Pin must be 4 digits");
} else {
System.out.println("Checking...");
}
Any ideas ? Thanks.
Put the check in client side code. For more info read inline comments.
Fist use nextLine() in place of next() to read a whole line at a time.
Validation check for password along with its length check
Here is the modified client side code. Please incorporate the changes.
...
PrintWriter out = new PrintWriter(clientSocket.getOutputStream());
System.out.println("Enter pin : ");
String password = null;
// 4 digits pattern
Pattern p = Pattern.compile("\\d{4}");
while (true) {
password = scanner.nextLine();
int pinSize = password.length();
if (pinSize == 4) {
Matcher m = p.matcher(password);
if (m.find()) {
System.out.println("Checking " + password);
break;
} else {
System.out.println("Pin must be 4 digits");
}
} else {
System.out.println("Pin must be 4 digits");
}
}
// send PIN to server
out.println(password);
...
I have two simple classes:
Client:
public static void main(String[] args) throws IOException {
InetAddress addr = InetAddress.getByName(null);
Socket socket = null;
try {
socket = new Socket(addr, 1050);
InputStreamReader isr = new InputStreamReader(socket.getInputStream());
in = new BufferedReader(isr);
OutputStreamWriter osw = new OutputStreamWriter( socket.getOutputStream());
BufferedWriter bw = new BufferedWriter(osw);
out = new PrintWriter(bw, false);
stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
// read user input
while (true) {
userInput = stdIn.readLine();
System.out.println("Send: " + userInput);
out.println(userInput);
out.flush();
String line = in.readLine();
while(line != null){
System.out.println(line);
line = in.readLine();
}
System.out.println("END");
}
}
catch (UnknownHostException e) {
// ...
} catch (IOException e) {
// ...
}
// close
out.close();
stdIn.close();
socket.close();
}
Server:
OutputStreamWriter osw = new OutputStreamWriter(socket.getOutputStream());
BufferedWriter bw = new BufferedWriter(osw);
PrintWriter out = new PrintWriter(bw, /*autoflush*/true);
private void sendMessage(String msg1, String msg2) {
out.println(msg1);
// empy row
out.println("");
out.println(msg2);
}
The user enters a message, and this is sent to the server. Then, the server responds with N messages.
After the first request, the client stops and is never printed the word "END".
How do I send multiple messages at different times, with only one socket connection?
Firstly, you don't need to send an empty row, because you are sending by "line" and recieving by "line".
out.println(msg1);
out.println(msg2);
and
userInput = stdIn.readLine();
Here, userInput will only equal msg1
What I would recommend, would be not to loop on stdIn.readLine() = null, but have the client send, for example, "END_MSG", to notify the server that it will not send anymore messages.
Perhaps something like...
SERVER:
userInput =stdIn.readLine();
if(userInput.Equals("START_MSG");
boolean reading=true;
while(reading)
{
userInput=stdIn.readLine();
if(userInput.Equals("END_MSG")
{
//END LOOP!
reading = false;
}
else
{
//You have received a msg - do what you want here
}
}
EDIT:CLIENT:
private void sendMessage(String msg1, String msg2) {
out.println("START_MSG");
out.println(msg1);
out.println(msg2);
out.println("END_MSG");
}
(It also looks like in your question to have mixed up the client and the server?)