The Artima Developer Community
Sponsored Link

Java Answers Forum
send a string from client to server

5 replies on 1 page. Most recent reply: Aug 18, 2017 8:51 PM by Priya Arrora

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 5 replies on 1 page
steps

Posts: 14
Nickname: spanishste
Registered: Nov, 2003

send a string from client to server Posted: Mar 2, 2004 1:49 AM
Reply to this message Reply
Advertisement
hallo,

could somebody please show me an example for sending a string from client to server.For ex:, If i get the value which is in a text field and save it in some variable, How can I send this value from client to server and when i send it to the server, it has to be in stored in some place so that I can use it later on the server.

Many many thanks for your help.


steps

Posts: 14
Nickname: spanishste
Registered: Nov, 2003

Re: send a string from client to server Posted: Mar 2, 2004 1:53 AM
Reply to this message Reply
oops, forgot to mention the type of client and server.Very simple socket communication.

Thanks once again

Viswanatha Basavalingappa

Posts: 84
Nickname: viswagb
Registered: Nov, 2003

Re: send a string from client to server Posted: Mar 3, 2004 3:13 AM
Reply to this message Reply
Hi,

Here is the sample Client Server Code ....

import java.io.*;
import java.net.*;
 
public class MyServer {
    public static void main(String args[]) {
 
        ServerSocket echoServer = null;
        String line;
        DataInputStream is;
        PrintStream os;
        Socket clientSocket = null;
 
// Try to open a server socket on port 9999
       try {
           echoServer = new ServerSocket(9999);
        }
        catch (IOException e) {
           System.out.println(e);
        }   
// Create a socket object from the ServerSocket to listen and accept 
// connections.
// Open input and output streams
 
try {
           clientSocket = echoServer.accept();
           is = new DataInputStream(clientSocket.getInputStream());
           os = new PrintStream(clientSocket.getOutputStream());
 
// As long as we receive data, echo that data back to the client.
 
           while (true) {
             line = is.readLine();
             os.println(line); 
           }
        }   
catch (IOException e) {
           System.out.println(e);
        }
    }
}
 
 
 
[b] Client code [/b]
import java.io.*;
import java.net.*;
 
public class MyClient {
    public static void main(String[] args) {
 
        Socket smtpSocket = null;  
        DataOutputStream os = null;
        DataInputStream is = null;
 
        try {
            smtpSocket = new Socket("hostname", 25);
            os = new DataOutputStream(smtpSocket.getOutputStream());
            is = new DataInputStream(smtpSocket.getInputStream());
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: hostname");
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to: hostname");
        }
 
	if (smtpSocket != null && os != null && is != null) {
            try {
 
				os.writeBytes("HELO\n"); 
				os.close();
                is.close();
                smtpSocket.close();   
            } catch (UnknownHostException e) {
                System.err.println("Trying to connect to unknown host: " + e);
            } catch (IOException e) {
                System.err.println("IOException:  " + e);
            }
        }
    }           
}


hope this helps you..let me know...

Viswa
------

Charles Bell

Posts: 519
Nickname: charles
Registered: Feb, 2002

Re: send a string from client to server Posted: Mar 5, 2004 9:43 AM
Reply to this message Reply
Simple Client Server is at:
http://www.quantumhyperspace.com/JavaProgramming/JavaSourceBank/viewCode.jsp?javaFile=SimpleClient.java
/*  SimpleClient.java
*  @author Charles Bell
*  @version December 15, 2000
*  email: charles@quantumhyperspace.com
*/
 
import java.io.*;
import java.net.*;
 
/**  Connects to a SimpleServer which is listening on port 8189
*/
public class SimpleClient{
 
  String serverurl = "127.0.0.1";
  int serverport = 8189;
 
  /**  Instantiates an instance of the SimpleClient class and initilaizes it.
  */
  public static void main(String[] args){
    SimpleClient simpleclient = new SimpleClient();
    simpleclient.init();
  }
 
  /**  Connects to the SimpleServer on port 8189 and sends a few demo lines
  *  to the server, and reads, displays the server reply,
  *  then issues a Bye command signaling the server to quit.
  */
  public void init(){
    Socket socket = null;    
    try{
      System.out.println("Connecting to " + serverurl + " on port " + serverport);
      socket = new Socket(serverurl,serverport);
      //Set socket timeout for 10000 milliseconds or 10 seconds just 
      //in case the host can't be reached
      socket.setSoTimeout(10000);
      System.out.println("Connected.");
      
      InputStreamReader inputstreamreader = new InputStreamReader(socket.getInputStream());
      BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
      //establish an printwriter using the output streamof the socket object
      //and set auto flush on    
      PrintWriter printwriter = new PrintWriter(socket.getOutputStream(),true);
      printwriter.println("Hey howze it going today!");
      printwriter.println("This is some anonymous user on the client side.");
      printwriter.println("Let's see what happens when I type this.");
      printwriter.println("Oh well, I've had enough.");
      printwriter.println("Bye");
      String lineread = "";
      while ((lineread = bufferedreader.readLine()) != null){
        System.out.println("Received from Server: " + lineread);
      }
      System.out.println("Closing connection.");
      bufferedreader.close();
      inputstreamreader.close();
      printwriter.close();
      socket.close();
      System.exit(0);
 
    }catch(UnknownHostException unhe){
      System.out.println("UnknownHostException: " + unhe.getMessage());
    }catch(InterruptedIOException intioe){
      System.out.println("Timeout while attempting to establish socket connection.");
    }catch(IOException ioe){
      System.out.println("IOException: " + ioe.getMessage());
    }finally{
      try{
        socket.close();
      }catch(IOException ioe){
        System.out.println("IOException: " + ioe.getMessage());
      }
    }
  }
}


SimpleServer:
http://www.quantumhyperspace.com/JavaProgramming/JavaSourceBank/viewCode.jsp?javaFile=SimpleServer.java

/*  SimpleServer.java
*  @author Charles Bell
*  @version December 15, 2000
*  email: charles@quantumhyperspace.com
*/
 
import java.io.*;
import java.net.*;
import java.util.*;
 
/**  When started allows one client to connect. It listens on port 8189.
*  It returns whatever a connected client sends.
*  It shuts down when the client sends a Bye line.
*
*/
public class SimpleServer{
 
  /**  Instantiates an instance of the SimpleServer class and initilaizes it.
  */
  public static void main(String[] args){
    SimpleServer simpleserver = new SimpleServer();
    simpleserver.init();
  }
 
  /**  Sets up a ServerSocket and listens on port 8189.
  */
  public void init(){
    ServerSocket serversocket = null;
    Socket socket = null;
    try{
      //establish a server socket monitoring port 8189 
      //port 8189 is not used by any services
      serversocket = new ServerSocket(8189);
      System.out.println("Listening at 127.0.0.1 on port 8189");
 
      //wait indefinitely until a client connects to the socket
      socket = serversocket.accept();
 
      //set up communications for sending and receiving lines of text data
      //establish a bufferedreaderr from the input stream provided by the socket object
      InputStreamReader inputstreamreader = new InputStreamReader(socket.getInputStream());
      BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
 
      //establish an printwriter using the output streamof the socket object
      //and set auto flush on    
      PrintWriter printwriter = new PrintWriter(socket.getOutputStream(),true);
 
      //for binary data use
      // DataInputStream and DataOutputStream
 
      //for serialized objects use
      // ObjectInputStream and ObjectOutputStream
 
      String datetimestring = (Calendar.getInstance()).getTime().toString();
      printwriter.println("You connected to the Simple Server at " + datetimestring);
      printwriter.println("Send Bye to disconnect.");
 
      String lineread = "";
      boolean done = false;
      while (((lineread = bufferedreader.readLine()) != null) && (!done)){
        System.out.println("Received from Client: " + lineread);
        printwriter.println("You sent: " + lineread);
        if (lineread.compareToIgnoreCase("Bye") == 0) done = true;
      }
      System.out.println("Closing connection.");
      bufferedreader.close();
      inputstreamreader.close();
      printwriter.close();
      socket.close();
    }catch(UnknownHostException unhe){
      System.out.println("UnknownHostException: " + unhe.getMessage());
    }catch(InterruptedIOException intioe){
      System.out.println("Timeout while attempting to establish socket connection.");
    }catch(IOException ioe){
      System.out.println("IOException: " + ioe.getMessage());
    }finally{
      try{
        socket.close();
        serversocket.close();
      }catch(IOException ioe){
        System.out.println("IOException: " + ioe.getMessage());
      }
    }
  }
} 

saeed saadatzi

Posts: 1
Nickname: saadatzi
Registered: Jun, 2017

Re: send a string from client to server Posted: Jun 21, 2017 10:57 PM
Reply to this message Reply
I can send a string after a file I sent.

this is my code:

ClientSide


//import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
//import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;

public class Client_R01 {

public final static int SOCKET_PORT = 13267; // you may change this
public final static String SERVER = "127.0.0.1"; // localhost
public final static String
FILE_TO_RECEIVED = "F:/E/C drive/fglog.txt"; // you may change this, I give a
// different name because i don't want to
// overwrite the one used by server...

public final static int FILE_SIZE = 6022386; // file size temporary hard coded
// should bigger than the file to be downloaded

public static void main (String [] args ) throws IOException {
int bytesRead;
int current = 0;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
Socket sock = null;
BufferedReader br = null;
try {
sock = new Socket(SERVER, SOCKET_PORT);
System.out.println("Connecting...");

// receive file
byte [] mybytearray = new byte [FILE_SIZE];
InputStream is = sock.getInputStream();
fos = new FileOutputStream(FILE_TO_RECEIVED);
bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;

do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);

bos.write(mybytearray, 0 , current);
bos.flush();
System.out.println("File " + FILE_TO_RECEIVED
+ " downloaded (" + current + " bytes read)");

String Fhash = MD5.getMD5(Byte_change(mybytearray));//Changing a Byte
br = new BufferedReader(new InputStreamReader(is));
String Rhash = br.readLine();

System.out.println("Right Hash is : " + Rhash);
System.out.println("False Hash is : " + Fhash);
}
finally {
if (fos != null) fos.close();
if (br !=null) br.close();
if (bos != null) bos.close();
if (sock != null) sock.close();
}
}
public static String Byte_change(byte[] b) {
// String s = b.toString();
StringBuilder s1 = new StringBuilder(b.toString());
s1.setCharAt(2, '#');
b = s1.toString().getBytes();
return s1.toString();
}
}
/////////////

ServerSide

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;


/**
*
* @author saeed
*/
public class server_R01 {

public final static int Socket_Port = 13267;
public final static String File_To_Send = "F:/E/C drive/Filter builder/fglog.txt";

public static void main (String [] args){
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
ServerSocket servsock = null;
Socket sock1 = null;
Socket sock2 = null;
PrintWriter pw = null;

try {
servsock = new ServerSocket(Socket_Port);
while (true) {
System.out.println("Waiting...");
try {
sock1 = servsock.accept();
System.out.println("Accepted connection : " + sock1);
// send file
File myFile = new File (File_To_Send);
byte [] mybytearray = new byte [(int)myFile.length()];

fis = new FileInputStream(myFile);
bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
os = sock1.getOutputStream();
System.out.println("Sending " + File_To_Send + "(" + mybytearray.length + " bytes)");
os.write(mybytearray,0,mybytearray.length);


String hash1 = MD5.getMD5(mybytearray.toString());
pw = new PrintWriter(os,true);
pw.write(hash1);

// pw.close();
// os.close();
os.flush();

System.out.println("Done.");
} catch (IOException ex){
System.out.println("Connection and sending of file is not occured.");
} finally {
if (bis != null) bis.close();
if (pw != null) pw.close();
if (os != null) os.close();
if (sock1!=null) sock1.close();
if (sock2!=null) sock2.close();
if (servsock != null) servsock.close();
}
}
}catch (IOException ex){
System.out.println("that doesn't work.");
}
}
}

Priya Arrora

Posts: 5
Nickname: priya456
Registered: Aug, 2017

Re: send a string from client to server Posted: Aug 18, 2017 8:51 PM
Reply to this message Reply
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server
{

private static Socket socket;

public static void main(String[] args)
{
try
{

int port = 25000;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server Started and listening to the port 25000");

//Server is running always. This is done using this while(true) loop
while(true)
{
//Reading the message from the client
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String number = br.readLine();
System.out.println("Message received from client is "+number);

//Multiplying the number by 2 and forming the return message
String returnMessage;
try
{
int numberInIntFormat = Integer.parseInt(number);
int returnValue = numberInIntFormat*2;
returnMessage = String.valueOf(returnValue) + "\n";
}
catch(NumberFormatException e)
{
//Input was not a number. Sending proper message back to client.
returnMessage = "Please send a proper number\n";
}

//Sending the response back to the client.
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("Message sent to the client is "+returnMessage);
bw.flush();
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
socket.close();
}
catch(Exception e){}
}
}
}

Flat View: This topic has 5 replies on 1 page
Topic: Programming Using JSP and servlets Previous Topic   Next Topic Topic: Who has the best java based tech stack in Raleigh NC

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use