Socket s1=new Socket("localhost",3001);
System.out.println("Client process");
byte b[]=new byte[150];
int n=4;
BufferedReader BR=new BufferedReader(new InputStreamReader(s1.getInputStream()));
String str=new String();
while((str=BR.readLine())!=null)
{
System.out.println();
System.out.println(str);
}
s1.close();
In the above code I'm trying to read a line from server and print that line on client machine.But the client couldn't read a line until the server is finished writing all lines and closed.Please help me how to read a line from server at a time.
Check if the server flushes its output stream after each line.
Client code :
Socket s1=new Socket("localhost",4444);
System.out.println("Client process");
byte b[]=new byte[150];
int n=4;
BufferedReader BR= new BufferedReader(new InputStreamReader(s1.getInputStream()));
String str=new String();
while((str=BR.readLine())!=null) {
System.out.println();
System.out.println(str);
}
s1.close();
Simple server code :
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
}
catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
}
catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
String inputLine, outputLine;
// write to client
for(int i=0;i<10;i++){
out.println("hello from server" + i);
Thread.sleep(1000);
System.out.println("Server sent " + i);
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
System.err.println("Server done.. closing now..");
PS : add these into main methods , and add the throws clause with appropriate exceptions.
Related
Can anybody help me with this here. I am a newbie and I am working on a network application where I have to create a socket connection to the IP address and port that they already given me and then send XML message to the socket and finally include the ReadMe.txt file where I will save what I have received from the server. Here's my code
private static Socket socket;
public static void main(String args[])
{
try
{
socket = new Socket( "196.37.22.179", 9011);
//Send the message to the server
//PrintStream outstrm = null;
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String str;
str = "<request>";
str += "<EventType>Authentication</EventType>";
str += "<event>";
str += "<UserPin>12345</UserPin>";
str += "<DeviceId>12345</DeviceId>";
str += "<DeviceSer>ABCDE</DeviceSer>";
str += "<DeviceVer>ABCDE</DeviceVer>";
str += "<TransType>Users</TransType>";
str += "</event></request>";
bw.write(str);
bw.flush();
System.out.println("Message sent to the server......! ");
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
You can use this code to store results from server in file
//Get the return message from the server
InputStream is = socket.getInputStream();
OutputStream outputStream = new FileOutputStream(new File("ReadMe.txt"));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
I need to make these code's multithreaded. I searched everywhere but i cant figure it out. Can you guys do it for me ?
Client.java's main method
Socket clientSocket = null;
PrintWriter out = null;
BufferedReader in = null;
String senddata;
try{
clientSocket = new Socket("localhost",5555);
}catch(IOException e){
System.out.println("Connection Error!");
}
out = new PrintWriter(clientSocket.getOutputStream(),true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.print("------------------------------------------------------------\nEnter The Data That Will Send The Server = ");
BufferedReader data = new BufferedReader(new InputStreamReader(System.in));
while(!(senddata = data.readLine()).equals("STOP")){
out.println(senddata);
System.out.println("Response The Client = " + in.readLine());
System.out.print("------------------------------------------------------------\nEnter The Data That Will Send The Server = ");
}
out.close();
in.close();
data.close();
clientSocket.close();
Server.java's main method
ServerSocket serverSocket = null;
Socket clientSocket = null;
String receivedData;
try{
serverSocket = new ServerSocket(5555);
}catch(IOException e){
System.out.println("Port Error!");
}
clientSocket = serverSocket.accept(); // Bağlantıyı Sağlayan Kod Satırı. Bağlantı Sağlanmadan Bir Alt Satıra Geçilmez.
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),true); // Clienta Veri Gönderimi İçin PrintWriter Nesnesi Oluşturuldu!
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); // Clientden Gelen Verileri Tutan BufferedReader Nesnesi Oluşturuldu!
while(!(receivedData = in.readLine()).equals("STOP")){
System.out.println("------------------------------------------------------------\nReceived Data From Client = " + receivedData);
System.out.println("Response = " + receivedData);
out.println(receivedData);
}
out.close();
in.close();
serverSocket.close();
clientSocket.close();
I have a threaded java client/server pair, and it's behaving really strange . Here is the server side :
public class sample_server {
private static int port=4444, maxConnections=0;
// Listen for incoming connections and handle them
public static void main(String[] args) {
int i=0;
try{
ServerSocket listener = new ServerSocket(port);
Socket server;
while((i++ < maxConnections) || (maxConnections == 0)){
doComms connection;
server = listener.accept();
doComms conn_c = new doComms(server);
Thread t = new Thread(conn_c);
t.start();
}
} catch (IOException ioe) {
System.out.println("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
}
}
class doComms implements Runnable {
private Socket server;
private String line,input;
doComms(Socket server) {
this.server=server;
}
public void run () {
input="";
try {
// Get input from the client
DataInputStream in = new DataInputStream (server.getInputStream());
PrintStream out = new PrintStream(server.getOutputStream());
while((line = in.readLine()) != null && !line.equals(".")) {
java.util.Date date = new java.util.Date();
String timeString = String.valueOf((date.getTime()));
input=input + line + timeString;
out.println("I got:" + line + " " + timeString + "\n");
}
// Now write to the client
System.out.println("Overall message is:" + input);
out.println("Overall message is:" + input);
server.close();
} catch (IOException ioe) { /* ETC BOILERPLATE */
And this is my client code :
public class sample_client {
public static void main(String[] args) throws IOException {
String serverHostname = new String ("127.0.0.1");
if (args.length > 0)
serverHostname = args[0];
System.out.println ("Attemping to connect to host " +
serverHostname + " on port 10007.");
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
// echoSocket = new Socket("taranis", 7);
echoSocket = new Socket(serverHostname, 4444);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + serverHostname);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: " + serverHostname);
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();
//END OLD CODE
}
}
When I run this code, on the clients it only displays the full "echo" line on every other round, like so :
input: hi
echo: I got:hi 1430872840921
input: ok
echo:
input: hi
echo: I got:ok 1430872842861
input: ok
echo:
input: hi
echo: I got:hi 1430872846214
input: ok
echo:
input:
thanks
PrintStream out = new PrintStream(server.getOutputStream());
You need the autoflush parameter here too, just as in the client where you construct the PrintWriter.
Or else call flush() after every println() in the server, if you can be bothered.
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 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?)