I have a project that has a server which creates an empty text file.
Once my client stops writing to this file, the server should read and display the results.
My problem is that the client is connecting to the server, but whatever text the client is sending is not being written on the server side. In addition, when I exit, the server doesn't quit.
This is what I have so far:
The Server
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server {
public static void main(String args[]) throws IOException {
BufferedWriter out;// = new BufferedWriter(new FileWriter("C://Users//Vagos//Desktop//file.txt"));
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(55);
}
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());
out = new BufferedWriter(new FileWriter("C://Users//Vagos//Desktop//file.txt"));
// As long as we receive data, echo that data back to the client.
while (true) {
line = is.readUTF();
os.println(line);
os.flush();
out.write(line);
out.flush();
}
}
catch (IOException e) {
System.out.println(e);
}
}
}
Here is my client:
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class client {
public static void main(String[] args) {
Socket smtpSocket = null;
DataOutputStream os = null;
DataInputStream is = null;
String strout;
Scanner in = new Scanner(System.in);
try {
smtpSocket = new Socket("localhost", 55);
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 {
do{
System.out.print("Write what the client will send: ");
strout = in.nextLine();
os.writeBytes(strout);}
while(!strout.equals("exit"));
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);
}
}
}
};
Try this.
In your server
// Open input and output streams
try {
clientSocket = echoServer.accept();
is = new DataInputStream(clientSocket.getInputStream());
InputStreamReader ir = new InputStreamReader(is);
BufferedReader br = new BufferedReader(ir);
os = new PrintStream(clientSocket.getOutputStream());
out = new BufferedWriter(new FileWriter("C://Users//Vagos//Desktop//file.txt"));
// As long as we receive data, echo that data back to the client.
while (true) {
line = br.readLine();
System.out.println(line);
os.println(line);
os.flush();
if( line != null ){
out.write(line + '\n');
out.flush();
}
}
}
And about the 'exit' part of your client try after changing
while(!strout.equals("exit"));
to
while(!strout.equalsIgnoreCase("exit"));
Hope this helps !!
Today my teacher is upload a new project because he has make a false , the project i have to make is similar which the old but the client is reading or writing a txt with number from 0-911, The client is choice randomly what is make read o write if choice read show the numbers of txt if choice write he write randomly a number from 0-911 and stop if choice the 100.
i make it but nothing show me is stack.
sever
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server {
public static void main(String args[]) throws IOException {
BufferedWriter out;// = new BufferedWriter(new FileWriter("C://Users//Vagos//Desktop//file.txt"));
ServerSocket echoServer = null;
int line;
DataInputStream is;
PrintStream os;
Socket clientSocket = null;
// Try to open a server socket on port 9999
try {
echoServer = new ServerSocket(55);
}
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());
InputStreamReader ir = new InputStreamReader(is);
BufferedReader br = new BufferedReader(ir);
os = new PrintStream(clientSocket.getOutputStream());
out = new BufferedWriter(new FileWriter("C://Users//Vagos//Desktop//file.txt"));
// As long as we receive data, echo that data back to the client.
boolean ch=true;
{
line =(Integer) br.read();
// System.out.println(line);
os.println(line);
os.flush();
out.write(line+"\n");
out.flush();
} while (line != 100);
os.close();
out.close();
br.close();
clientSocket.close();
}
catch (IOException e) {
System.out.println(e);
}
}
}
client
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Random;
import java.util.Scanner;
public class client {
public static void main(String[] args) throws IOException {
Socket smtpSocket = null;
DataOutputStream os = null;
DataInputStream is = null;
String strout;
int number=0;
Random rand = new Random(System.currentTimeMillis());
Scanner in = new Scanner(System.in);
try {
smtpSocket = new Socket("localhost", 55);
os = new DataOutputStream(smtpSocket.getOutputStream());
is = new DataInputStream(smtpSocket.getInputStream());
} catch (UnknownHostException e) {
System.err.println("Don't know about host: localhost");
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: localhost");
}
int choice=2;//rand.nextInt(2);
if(choice==1){
int num=is.read();
System.out.println(num);
}
else if(choice==2){
try {
do{
number=rand.nextInt(911);
// System.out.println(number);
os.writeInt(number);
}while(number!=100);
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);
}
}
}
}
Related
I have problem in this code that client could send message to server but it doesn't receive the message sent from server I've debugged the server code it does everything as well as it should be but client sided it does all the code until message=br.readLine() , it sticks on there
server code
package server;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class server {
static Socket s;
static ServerSocket ss;
static InputStreamReader isr;
static BufferedReader br;
static String message;
static PrintWriter pw;
public server(){
try {
ss=new ServerSocket(8080);
while(true){
s=ss.accept();
isr=new InputStreamReader(s.getInputStream());
br=new BufferedReader(isr);
message=br.readLine();
System.out.println(message);
pw=new PrintWriter(s.getOutputStream(),true);
pw.write("returned back from server to client");
System.out.println("message sent");
pw.flush();
pw.close();
isr.close();
s.close();
}
} catch (EOFException eofException) {
// TODO Auto-generated catch block
eofException.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
public static void main(String[]args){
server s=new server();
}
}
client code
package com.example.myapplication;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class ClientSender extends AsyncTask<String,Void,Void> {
Socket s;
DataOutputStream dos;
InputStreamReader isr;
BufferedReader br;
PrintWriter pw;
#Override
protected Void doInBackground(String... voids) {
String message = voids[0];
try {
System.out.println("1");
s = new Socket("0.0.0.0", 8080);
pw = new PrintWriter(s.getOutputStream());
pw.write(message);
pw.flush();
pw.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
System.out.println("2");
s = new Socket("0.0.0.0", 8080);
System.out.println("connected to the server");
isr = new InputStreamReader(s.getInputStream());
System.out.println("3");
br = new BufferedReader(isr);
System.out.println("4");
message = br.readLine();
System.out.println(message);
isr.close();
s.close();
System.out.println("5");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
I would suggest you to use Socket.IO instead of writting your own socket client. It's a well-tested and well-documented lib. This will make your life pretty much easier.
Both ran successfully, but they skipped some parts, I don't know why. Here are the codes
Client:
package echoapp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
public class SimpleEchoClient {
public static void main(String[] args) throws IOException{
System.out.println("Simple Echo Client");
try {
System.out.println("Waiting for connection.....");
InetAddress localAddress = InetAddress.getLocalHost();
try (Socket clientSocket = new Socket(localAddress, 6000);
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))){
System.out.println("Connected to server");
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Enter text: ");
String inputLine = scanner.nextLine();
if ("quit".equalsIgnoreCase(inputLine)) {
break;
}
out.println(inputLine);
String response = br.readLine();
System.out.println("Server response: " + response);
}
}
} catch (IOException ex) {
// Handle exceptions
}
}
}
Server:
package echoapp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleEchoServer {
public static void main(String[] args)throws IOException {
System.out.println("Simple Echo Server");
try (ServerSocket serverSocket = new ServerSocket(6000)){
System.out.println("Waiting for connection.....");
Socket clientSocket = serverSocket.accept();
System.out.println("Connected to client");
try (BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {
String inputLine;
while((inputLine = br.readLine()) != null) {
System.out.println("Server: " + inputLine);
out.println(inputLine);
}
}
} catch (IOException ex) {
// Handle exceptions
}
}
}
I should be able to type something in the client and get the response from the server. Like echo. I don't know why how to fix the try block to make all the codes ran through. The parts where the second try has a problem, and I couldn't make the second try block work.
I'm trying made a simple video stream with Java.I got that play some mp4 video,but not all. On the other hand, I can't seek the stream when the video is playing(Tried in VLC and Chrome). I like to know: What problems does my code have?
Here is the code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Xerver {
protected void start() {
ServerSocket s;
Socket remote;
OutputStream out;
System.out.println("Webserver starting up on port 8080");
try {
// create the main server socket
s = new ServerSocket(8080);
} catch (IOException e) {
System.out.println("Error: " + e);
return;
}
System.out.println("Waiting for connection");
for (;;) {
try {
// wait for a connection
remote = s.accept();
// remote is now the connected socket
System.out.println("Connection, sending data.");
BufferedReader in = new BufferedReader(new InputStreamReader(remote.getInputStream()));
FileInputStream fs;
out = remote.getOutputStream();
File file = new File("D:\\stream.mp4");
out.write("HTTP/1.0 200 OK\r\n".getBytes());
out.write("Content-Type: video/mp4\r\n".getBytes());
out.write("Accept-Ranges: bytes\r\n".getBytes());
out.write(String.format("Content-Length:%s\r\n\r\n",Long.toString(file.length())).getBytes());
fs = new FileInputStream(file);
final byte[] buffer = new byte[1024];
int count = 0;
do{
count = fs.read(buffer);
out.write(buffer, 0, count);
}
while (count <= 1024);
out.flush();
remote.close();
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
}
public static void main(String args[]) {
Xerver ws = new Xerver();
ws.start();
}
}
Thanks in advance
I wrote a Simple Server Client Program and when I start the Server and the Client, the Client gets the message which it sent to the Server back and terminates itself. But when i start another Client it does not get the message back. Why?
Thanks alot!
First class: the client
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class StringClient {
public static void main(String[] args) {
Socket socket = null;
try{
socket = new Socket("localhost", 3141);
OutputStream raus = socket.getOutputStream();
PrintStream ps = new PrintStream(raus, true);
System.out.println("1");
ps.println("Hello World!");
ps.println("Hello Universe!");
InputStream rein = socket.getInputStream();
System.out.println("verf\u00FCgbare Bytes: " + rein.available());
BufferedReader br =new BufferedReader(new InputStreamReader(rein));
System.out.println(2);
while(br.ready()){
System.out.println(br.readLine());
}
}catch(UnknownHostException e ){
System.out.println("Unknown Host...");
e.printStackTrace();
} catch (IOException e) {
System.out.println("IOProbleme...");
e.printStackTrace();
}finally{
if(socket != null){
try{
socket.close();
System.out.println("Socket geschlossen...");
}catch(IOException e){
System.out.println("Fehler beim Schließen des Sockets!");
e.printStackTrace();
}
}
}
}
}
Second class: the Server
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class StringServer {
private final ServerSocket server;
public StringServer(int port) throws IOException {
server = new ServerSocket(port);
}
private void connect(){
while(true){
Socket socket = null;
try{
socket = server.accept();
reinRaus(socket);
}catch(IOException e){
e.printStackTrace();
}finally{
if(socket != null){
try{
socket.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
}
private void reinRaus(Socket socket) throws IOException{
BufferedReader rein = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream raus = new PrintStream(socket.getOutputStream());
String s;
while(rein.ready()){
s = rein.readLine();
raus.println(s);
}
}
public static void main(String[] args) throws IOException {
StringServer server = new StringServer(3141);
server.connect();
}
}
The main thread should allocates individual/different threads to the incoming clients, so different clients get allocated for different threads (they get different sockets). In your current code there's only a server serving a client.
StringServer.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class StringServer {
private final ServerSocket server;
public StringServer(int port) throws IOException {
server = new ServerSocket(port);
}
private void connect(){
while(true){
Socket socket = null;
try{
socket = server.accept();
clientHandler ch = new clientHandler(socket);
ch.start();
}catch(IOException e){
e.printStackTrace();
}finally{
if(socket != null){
try{
socket.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) throws IOException {
StringServer server = new StringServer(3541);
server.connect();
}
}
class clientHandler extends Thread {
Socket client;
public clientHandler(Socket client) {
this.client = client;
}
#Override
public void run() {
try {
BufferedReader rein = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintStream raus = new PrintStream(client.getOutputStream(),true);
String s;
while(rein.ready()){
s = rein.readLine();
raus.println(s);
}
client.close(); // IOException
} catch (IOException e) {
}
}
}
StringClient.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class StringClient {
public static void main(String[] args) {
Socket socket = null;
try{
socket = new Socket("localhost", 3541);
OutputStream raus = socket.getOutputStream();
PrintStream ps = new PrintStream(raus, true);
System.out.println("1");
ps.println("Hello World!");
ps.println("Hello Universe!");
InputStream rein = socket.getInputStream();
System.out.println("verf\u00FCgbare Bytes: " + rein.available());
BufferedReader br =new BufferedReader(new InputStreamReader(rein));
System.out.println(2);
while(br.ready()){
System.out.println(br.readLine());
}
}catch(UnknownHostException e ){
System.out.println("Unknown Host...");
e.printStackTrace();
} catch (IOException e) {
System.out.println("IOProbleme...");
e.printStackTrace();
}finally{
if(socket != null){
try{
socket.close();
System.out.println("Socket geschlossen...");
}catch(IOException e){
System.out.println("Fehler beim Schließen des Sockets!");
e.printStackTrace();
}
}
}
}
}
I am trying to develop a client/Server communication application in java. But at the very initial stage I am unable to read data string from the socket's Output stream using BufferedReader.readline(). I have googled a lot but could not find the specific answer to my question.Debugging the client application shows that the client application halts at response.readline().
Server:
package myserver;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MyServer {
public static void main(String[] args) {
String[] tokens = new String[10];
int count = 0;
ServerSocket server = null;
try {
server = new ServerSocket(16);
} catch (IOException ex) {
Logger.getLogger(OdeskServer.class.getName()).log(Level.SEVERE, null, ex);
}
if (server != null) {
while (true) {
PrintWriter response;
BufferedReader command;
String inCommand;
try {
Socket client = server.accept();
System.out.println("Connected!");
response = new PrintWriter(client.getOutputStream());
command = new BufferedReader(new InputStreamReader(client.getInputStream()));
response.print("EHLO\r\n");
command.read(); //just to stop the application to start a new iteration
} catch (IOException ex) {
Logger.getLogger(OdeskServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
Client:
package myclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MyClient {
public static void main(String[] args) {
Socket server = null;
PrintWriter command;
BufferedReader response;
BufferedReader Console = new BufferedReader(new InputStreamReader(System.in));
try {
server = new Socket("175.107.231.218", 16);
System.out.println("Connected");
command = new PrintWriter(server.getOutputStream());
response = new BufferedReader(new InputStreamReader(server.getInputStream()));
while (server.isBound()) {
String input = response.readLine(); //Here is where the communication halts
System.out.print(input);
}
} catch (UnknownHostException ex) {
Logger.getLogger(OdeskClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(OdeskClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Any idea about this issue?
You may need to call response.flush() from the server to ensure that the socket does not buffer your message waiting for more writes to batch together.