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.
Related
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 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 have created two Java programs, a server and a client which can communicate with each other, if they're executed on the same PC.
Server:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Server {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(30);
ServerSocket server;
try {
server = new ServerSocket(5555);
System.out.println("Server gestartet!");
while(true){
try {
Socket client = server.accept();
//Thread t = new Thread(new Handler(client));
//t.start();
executor.execute(new Handler(client));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
Handler (Server creates each time an instance when a new client joins):
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
public class Handler implements Runnable {
private Socket client;
public Handler(Socket client) {
this.client = client;
}
#Override
public void run() {
try{
//Streams
OutputStream out = client.getOutputStream();
PrintWriter writer = new PrintWriter(out);
InputStream in = client.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
// ------------------------------
String s = null;
while((s = reader.readLine()) != null){
writer.write(s + "\n");
writer.flush();
System.out.println("Empfangen vom Client: " + s);
}
writer.close();
reader.close();
client.close();
}catch(Exception e){}
}
}
Client:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
try {
Socket client = new Socket("localhost", 5555);
System.out.println("Client gestartet!");
//Streams
OutputStream out = client.getOutputStream();
PrintWriter writer = new PrintWriter(out);
InputStream in = client.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
// ------------------------------
writer.write("Hallo Server!\n");
writer.flush();
String s = null;
while((s = reader.readLine()) != null){
System.out.println("Empfangen vom Server: " + s);
}
reader.close();
writer.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
My question now is:
How can make a server on my computer which can be accessed via Internet? My first thougt was to change something in the constructor of the client socket
Socket client = new Socket("localhost", 5555);
"localhost" probably means that the server runs on the same PC as the client.
My goal would be to have an app on my smartphone which connects via Internet to my server which runs on my PC. It should send back my message I entered.
Get your public IP address using http://whatismyip.com
Change the client code to Socket client = new Socket("<replace_with_your_public_ip>", 5555);
Make sure the client is allowed to open outgoing connections to port 5555 (this is usually the case if connected in Wifi, but not if you are using 3G/4G)
Configure the router to which your server is connected, so that it redirects incoming connections from the Internet on port 5555 to the IP of your server on the LAN (still on port 5555). This kind of settings usually can be found in a section called "NAT", in the router admin console (usually accessible via http://192.168.0.1 or http://192.168.1.1 depending on the router model).
I'm new to java socket programming, this program allows TCP server to have a multi-thread that can run concurrently. I try to send the txt file from one client(has another client that will sent file at the same time) to the server side and ask server to send "ok" status message back to client side. But it seems that the server can't receive any file from the client and the strange thing is if i delete the receiveFile() method in my client class, the server is able to recieve the file from client. Can somebody help me?
Server.class
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
public class ConcurrentServer {
public static void main(String args[]) throws IOException
{
int portNumber = 20020;
ServerSocket serverSocket = new ServerSocket(portNumber);
while ( true ) {
new ServerConnection(serverSocket.accept()).start();
}
}
}
class ServerConnection extends Thread
{
Socket clientSocket;
ServerConnection (Socket clientSocket) throws SocketException
{
this.clientSocket = clientSocket;
setPriority(NORM_PRIORITY - 1);
}
public void run()
{
try{
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
OutputStream outToClient = clientSocket.getOutputStream();
PrintWriter printOutPut = new PrintWriter(outToClient,true);
while(inFromClient.ready())
{
String request = inFromClient.readLine();
System.out.println(request);
System.out.println("test");
}
printOutPut.write("HTTP/1.1 200 OK\nConnection: close\n\n");
printOutPut.write("<b> Hello sends from Server");
printOutPut.flush();
printOutPut.close();
clientSocket.close();
}
catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
Client.class
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class SmallFileClient {
static String file="test.txt";
static PrintWriter outToServer;
static Socket socket;
public static void main(String[] args) throws IOException
{
final int PORT=20020;
String serverHostname = new String("127.0.0.1");
socket = new Socket(serverHostname, PORT);
outToServer = new PrintWriter(socket.getOutputStream(),true);
sendFile();
receiveFile();
outToServer.flush();
outToServer.close();
socket.close();
}
//read file and send file to server
public static void sendFile() throws IOException
{
BufferedReader br=new BufferedReader(new FileReader(file));
try
{
String line = br.readLine();
while(line!=null)
{
//send line to server
outToServer.write(line);
line=br.readLine();
}
}catch (Exception e){System.out.println("!!!!");}
br.close();
}
//get reply from server and print it out
public static void receiveFile() throws IOException
{
BufferedReader brComingFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
try
{
String inline = brComingFromServer.readLine();
while(inline!=null)
{
System.out.println(inline);
inline = brComingFromServer.readLine();
}
}catch (Exception e){}
}
}
Get rid of the ready() test. Change it to:
while ((line = in.readLine()) != null)
{
// ...
}
readLine() will block until data is available. At present you are stopping the read loop as soon as there isn't data available to be read without blocking. In other words you are assuming that `!ready()! means end of stream. It doesn't: see the Javadoc.
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);
}
}
}
}