I have made a connection between my phone and my computer using the Socket-framework. It work fine as long as i only need to send one command. Then i have to restart my server to recieve a new command. Can you help me figure out why? I'd like to be able to send multiple commands.
I'm calling the class-methods from a GUI-main-class.
My server code:
public class Server {
private static PrintWriter out;
private static BufferedReader in;
private static ServerSocket serverSocket = null;
private static Socket clientSocket = null;
private static String inputLine, outputLine;
public static void main() throws IOException {
try {
serverSocket = new ServerSocket(4444);
System.out.println(serverSocket.getInetAddress().toString());
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(1);
}
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
Protocol kkp = new Protocol();
outputLine = kkp.processInput(null);
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
outputLine = kkp.processInput(inputLine);
out.println(outputLine);
}
}
public static void shutDown() throws IOException
{
System.exit(1);
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
And my client code:
class ClientThread implements Runnable {
public void run() {
Socket kkSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
kkSocket = new Socket(serverAddr, 4444);
out = new PrintWriter(kkSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
} catch (UnknownHostException e) {
showToast("Kan ikke finde host fra: "+settings.getString("ip", "86.52.16.102"));
System.err.println("Don't know about host: taranis.");
System.exit(1);
} catch (IOException e) {
showToast("Kan ikke udveksle oplysninger med: "+settings.getString("ip", "86.52.16.102"));
System.err.println("Couldn't get I/O for the connection to: taranis.");
System.exit(1);
}
String fromServer;
String fromUser;
try {
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("Shutting down") || fromServer.equals("Wrong pin!"))
{
showToast(fromServer);
break;
}
//fromUser = stdIn.readLine();
fromUser = pinkode.getText().toString()+","+time;
if (fromUser != null) {
System.out.println("Client: " + fromUser);
out.println(fromUser);
fromUser = null;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.close();
try {
in.close();
kkSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Try to put this part of the code:
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
Protocol kkp = new Protocol();
outputLine = kkp.processInput(null);
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
outputLine = kkp.processInput(inputLine);
out.println(outputLine);
}
Inside a while(true){ ... }.
Related
Server application and client application are running in different computers. I want to send some message from client to server. The server should receive it and display. But in my case it's not happening. Nothing happens in server computer when something is sent.
This is my client program:
import java.io.*;
import java.net.*;
public class EchoClient {
//private static final String IP="194.47.46.36";
public EchoClient() {
}
public void establish() {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
//echoSocket = new Socket(InetAddress.getLocalHost(), 8080);
echoSocket = new Socket("195.47.46.76", 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.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
try {
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
if (userInput.equals("Bye."))
break;
System.out.println("echo: " + in.readLine());
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
} catch (IOException ioe) {
System.out.println("Failed");
System.exit(
-1);
}
}
}
Apologies as I asked something similar last night, but I have narrowed my problem down. I am wondering how to make my Java TCP Socket Server read in the data sent using the printWriter(out) in the Client code from a GUI as it does from the command line stdin.
I have the following classes as an example and everything works fine until the GUI comes into the equation. The data is being sent over to the Server from the GUI as I can echo it on the server side, but it is not being read and parsed properly as the stdin is. Nothing is being sent back to the client. I have tried flushing, using different streams and adding line separators all over the place to no avail. There is also a Protocol class that handles the data on the Server side.
public class KnockKnockServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
System.out.println("Waiting for client...");
} 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;
KnockKnockProtocol kkp = new KnockKnockProtocol();
outputLine = kkp.processInput(null);
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
outputLine = kkp.processInput(inputLine);
out.println(outputLine);
if (outputLine.equals("Bye.")) {
break;
}
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
.
public class KnockKnockClient {
public static PrintWriter out = null;
public static String sendAnswer;
public static void Client() {
//JButton Action Listener
saveAnswer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ButtonModel b = group.getSelection();
if (b.getActionCommand() == "A") { sendAnswer = radioA.getText(); }
String data = "รท" + sendAnswer;
out.println(data);
}
});
}
public static void main(String[] args) throws IOException {
KnockKnockClient.Client();
Socket kkSocket = null;
//PrintWriter out = null;
BufferedReader in = null;
try {
kkSocket = new Socket("localhost", 4444);
out = new PrintWriter(kkSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: localhost.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: localhost.");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer, fromUser;
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("Bye."))
break;
fromUser = stdIn.readLine();
if (fromUser != null) {
System.out.println("Client: " + fromUser);
out.println(fromUser);
}
}
out.close();
in.close();
stdIn.close();
kkSocket.close();
}
}
I have Socket- Client application. The code below is supposed to allow client to both read replies from server and read input at the same time. The thing is- this code "works" while debugging in eclipse, as in I recieve messages outside of normal flow in a process I'm debugging, but If i launch application normally, it completly ignores that proces? What is the most common cause of "IDE working, real life not" syndrome?
Whole files:
Server:
public class Server implements Runnable {
static ServerSocket serverSocket;
Socket tempSocket;
Socket tempSocket2;
static volatile List<User> usersList = new ArrayList<User>();
static boolean waitForNew = true;
PrintWriter tempOut;
volatile User[] tempUser;
volatile boolean isReadingN = false;
public Server(Socket _s, Socket _s2) {
tempSocket = _s;
tempSocket2 = _s2;
}
public Server(PrintWriter nOut, User[] user) {
tempOut = nOut;
tempUser = user;
isReadingN = true;
}
#Override
public void run() {
if (isReadingN) {
while (true) {
if (tempUser != null && tempUser.length > 0
&& tempUser[0] != null)
break;
}
User[] myUser = new User[1];
myUser[0] = tempUser[0];
// myUser[0]=usersList.
while (true) {
if (myUser[0].isCurrentlyLoggedIn() == false)
break;
String[] toSend = null;
if (myUser[0].isNotificable())
toSend = myUser[0].printNotifications().split("\n");
else
continue;
//tempOut.println("");
int sendL=toSend.length;
tempOut.println(String.valueOf(sendL));
for (int i = 0; i < toSend.length; i++)
tempOut.println(toSend[i]);
}
return;
}
Socket clientSocket = tempSocket;
System.out.println("Initiating conversation with the client");
String inputLine;
try {
System.out.print("creating server out...");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
Socket iClientSocket = tempSocket2;
ObjectOutputStream iout = new ObjectOutputStream(
iClientSocket.getOutputStream());
System.out.println("OK!");
System.out.print("creating server in...");
BufferedReader in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
System.out.println("OK!");
System.out.print("creating server image streams...");
System.out.println("OK!");
System.out.println("Server initiating conversation");
User[] currentUser = new User[1];
new Thread(new Server(out, currentUser)).start();
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
boolean[] downloadPicture = new boolean[1];
downloadPicture[0] = false;
String input = Command.call(inputLine, currentUser, usersList,
downloadPicture);
String[] toSend;
if (input != null) {
toSend = input.split("\n");
} else
toSend = new String[0];
out.println(String.valueOf(toSend.length));
for (int i = 0; i < toSend.length; i++)
out.println(toSend[i]);
if (downloadPicture[0]) {
System.out.println("File sent.");
iin.close();
} else{
out.println("1");
out.println("Error: File does not exit.");}
} else
//out.println(" ");
if (inputLine.equals("EXIT")) {
waitForNew = false;
break;
}
}
// End communication graciously
System.out.println("Closing sockets, closing streams");
out.close();
in.close();
clientSocket.close();
serverSocket.close();
} catch (IIOException e) {
System.out.println("Error: Could not find file");
e.printStackTrace();
System.exit(-1);
} catch (IOException e) {
System.out.println("Error");
e.printStackTrace();
System.exit(-1);
}
}
public static void main(String[] args) {
// Create socket on port given in argument, localhost
if (args.length == 0) {
System.out
.println("Not enough arguments. Try Server <port number>");
System.exit(-1);
}
int port = 0;
try {
port = Integer.valueOf(args[0]);
System.out.println("Application start");
serverSocket = new ServerSocket(port);
System.out.println("Created socket on port " + port);
} catch (NumberFormatException c) {
System.out
.println("Incorrect port number. Try Server <port number>");
System.exit(-1);
} catch (IOException e) {
System.exit(-1);
}
// Waiting for client
System.out.println("Waiting for client...");
Socket clientSocket = null;
Socket iClientSocket = null;
while (waitForNew) {
try {
clientSocket = serverSocket.accept();
iClientSocket = serverSocket.accept();
new Thread(new Server(clientSocket, iClientSocket)).start();
} catch (IOException e) {
System.out.println("Accept failed: " + port);
System.exit(-1);
}
}
}
}
Client:
public class Client implements Runnable {
static Socket clientSocket = null;
static Socket iClientSocket = null;
static PrintWriter out = null;
static BufferedReader in = null;
static InputStream iin = null;
public static void main(String[] args) {
int port = Integer.valueOf(args[1]);
String host = args[0];
try {
clientSocket = new Socket(host, port);
iClientSocket = new Socket(host, port);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
iin = iClientSocket.getInputStream();
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + host);
System.exit(-1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for " + "the connection to: "
+ host);
System.exit(-1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(
System.in));
String userInput;
try {
new Thread(new Client()).start();
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
}
System.out.println("Closing sockets, closing streams");
out.close();
in.close();
stdIn.close();
iClientSocket.close();
clientSocket.close();
} catch (IOException e) {
System.exit(-1);
}
}
#Override
public void run() {
String a = null;
try {
while (true) {
if((a = in.readLine()) == null)
continue;
int n;
try{
n = Integer.valueOf(a);
}catch(NumberFormatException e){
System.out.println(a);
n=1;
//continue;
}
a = "";
for (int i = 0; i < n; i++)
a += in.readLine() + "\n";
System.out.println(a);
// if(a.contains("POST"),)
if (a.compareToIgnoreCase("EXIT") == 0) {
System.out.println("Exiting");
break;
}
if (a.endsWith("Sending File\n")) {
System.out.println("Recieving image.");
(some unimportant for now code)
System.out.println("Image recieved");
}
}
} catch (IOException e) {
}
}
}
I have a problem when the client send data to the server. When I send data from the server to the client everything is okay. I received this message: "client receive: message" but then when I send "client's message", my server do not receive it.
import java.io.IOException;
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) throws IOException {
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;
outputLine = "message";
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
System.out.println("server receive: " + inputLine);
outputLine = "second message";
out.println(outputLine);
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == startButton) {
this.main.getContentPane().remove(homePanel);
String name = this.name.getText();
String result;
try {
connectionToServer();
if ((result = in.readLine()) != null) {
System.out.println("client receive: " + result);
out.println("client's message");
}
} catch(IOException err) {
System.out.println("error");
}
}
}
public void connectionToServer() throws IOException {
try {
this.socket = new Socket("localhost", 4444);
this.in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
this.out = new PrintWriter(this.socket.getOutputStream(), true);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: taranis.");
System.exit(1);
}
}
your actionPerformed method just link the server and do nothing.
The server closed after send a message.
watch: while ((inputLine = in.readLine()) != null)
if client don't send any message,code will break,then you closed the server.
I'm having problems with broadcasting the messages sent by each client. The server can receive each message from multiple clients but it cannot broadcast it. Error message says connection refused
Client:
public void initializeConnection(){
try {
host = InetAddress.getLocalHost();
try{
// Create file
FileWriter fstream = new FileWriter("src/out.txt", true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(host.getHostAddress()+'\n');
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
clientSocket = new Socket(host.getHostAddress(), port);
outToServer = new PrintWriter(clientSocket.getOutputStream(), true);
inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}
catch(IOException ioEx) {
ioEx.printStackTrace();
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==quit){
try {
outToServer.close();
clientSocket.close();
System.exit(1);
} catch (IOException e1) {
e1.printStackTrace();
}
}
else if(e.getSource()==button){
if(outMsgArea.getText()!=null || !outMsgArea.getText().equals("")){
String message = outMsgArea.getText();
outToServer.println(clientName+": "+message);
outMsgArea.setText("");
}
}
}
public void run(){
try {
while(true){
String message = inFromServer.readLine();
System.out.println(message);
inMsgArea.append(message+'\n');
}
} catch (IOException e) {
e.printStackTrace();
}
}
Server:
import java.io.*;
import java.net.*;
import java.util.*;
public class RelayChatServer {
public static int port = 44442;
ServerSocket server;
public void listenSocket(){
try{
server = new ServerSocket(port);
} catch (IOException e) {
System.out.println("Could not listen on port 4444");
System.exit(-1);
}
while(true){
ClientWorker w;
try{
//server.accept returns a client connection
w = new ClientWorker(server.accept());
Thread t = new Thread(w);
t.start();
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
}
}
}
protected void finalize(){
//Objects created in run method are finalized when
//program terminates and thread exits
try{
server.close();
} catch (IOException e) {
System.out.println("Could not close socket");
System.exit(-1);
}
}
public static void main(String[] args) {
new RelayChatServer().listenSocket();
}
}
class ClientWorker implements Runnable {
private Socket client;
//Constructor
ClientWorker(Socket client) {
this.client = client;
}
public void run(){
String line;
BufferedReader in = null;
PrintWriter out = null;
try{
in = new BufferedReader(new
InputStreamReader(client.getInputStream()));
//out = new
// PrintWriter(client.getOutputStream(), true);
} catch (IOException e) {
System.out.println("in or out failed");
System.exit(-1);
}
while(true){
try{
line = in.readLine();
//Send data back to client
//out.println(line);
//Append data to text area
if(line!=null && line!=""){
System.out.println(line);
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("out.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
Socket s;
PrintWriter prnt;
while ((strLine = br.readLine()) != null && (strLine = br.readLine()) != "") {
// Print the content on the console
s = new Socket(strLine, 44441);
prnt = new PrintWriter(s.getOutputStream(),true);
prnt.println(line);
System.out.println(strLine);
prnt.close();
s.close();
}
//Close the input stream
//inp.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}catch (IOException e) {
System.out.println("Read failed");
e.printStackTrace();
System.exit(-1);
}
}
}
}
The Exception starts:
java.net.ConnectException: Connection refused: connect
The expanded output looks like:
I'm somewhat confused as to why you attempt to open a new socket (do you intend for this to be sent back to the client?) based on a string you read from a file. Perhaps
s = new Socket(strLine, 44441);
prnt = new PrintWriter(s.getOutputStream(),true);
should be:
prnt = new PrintWriter(client.getOutputStream(),true);
As currently I don't see where you are sending anything back to the client.
Edit: ok try something like the following:
static final ArrayList<ClientWorker> connectedClients = new ArrayList<ClientWorker>();
class ClientWorker implements Runnable {
private Socket socket;
private PrintWriter writer;
ClientWorker(Socket socket) {
this.socket = socket;
try {
this.writer = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException ex) { /* do something sensible */ }
}
public void run() {
synchronized(connectedClients) {
connectedClients.add(this);
}
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) { /* do something sensible */ }
while (true) {
try {
String line = in.readLine();
if (line != null && line != "") {
synchronized (connectedClients) {
for (int i = 0; i < connectedClients.size(); ++i){
ClientWorker client = connectedClients.get(i);
client.writer.println(line);
}
}
}
} catch (IOException e) { /* do something sensible */ }
}
}
}