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();
Related
I'm trying to implement basic TCP communication via sockets and the problem is that it doesn't work. When I enter few sentences from client, the server receives only the first sentence and reply it back.
Client :
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 5055);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
while(!(sentence = inFromUser.readLine()).equals("end")) {
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
}
clientSocket.close();
Server:
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(5055);
while (true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
}
I am trying to pass message from server to client in terminal. What I would like the program to do is, in the client, it should be able to enter a command, get response from server, and be able to enter another command without restarting Client (by java Client).
Client.java
Socket socket = new Socket(host, port);
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String response = "";
boolean continuation = true;
while(continuation) {
Scanner input = new Scanner(System.in);
String command = (input.nextLine()).toString();
bw.write(command+"\r\n");
bw.flush();
if(command.equals("cmd1") {
while ((response = br.readLine()) != null) {
System.out.println(response);
}
}
System.out.println("This line will not execute as well.");
}
Server.java
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String[] in = br.readLine().split("\\s+");
String command = in[0];
if(command.equals("cmd1")) {
String response = "";
response = response + "RESPONSE:\r\n";
response = response + "This is a response.\r\n";
bw.write(response);
bw.flush();
}
If I don't put while((response = br.readLine()!= null) { ... } in Client.java, it is possible to enter multiple inputs in the terminal, but if I put it, it prints the response from the server and another input cannot be done without restarting Client.
Any help would be appreciated.
Thanks
This should work:
server:
DataInputStream dis = new DataInputStream(socket.getInputStream());
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
boolean continuation = true;
while (continuation) {
String command = dis.readUTF();
//proceeed command
dos.writeUTF("response");
dos.flush();
}
Client:
DataInputStream dis = new DataInputStream(socket.getInputStream());
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
dos.writeUTF("your command");
while (dis.available() == 0) {
try {
//wait for response
Thread.sleep(1);
} catch (InterruptedException ex) {
Logger.getLogger(RandomTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
String response = dis.readUTF();
//and so on
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 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?)
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.