I'm trying to create a Java program as a proxy to view packets from an incoming source to debug. To do this, I have created a simple Java server application and have edited my host file on the device. Everything works fine as of now, (even my Relay class file) but I am trying to make it into a full fledged proxy. How could I incorporate elements to send data to the server, and send the response back to the client? Sort of like a Man-In-The-Middle type of thing.
import java.net.*;
import java.io.*;
import org.ini4j.Ini;
public class RelayMultiClient extends Thread {
private Socket socket = null;
Socket relay = null;
public RelayMultiClient(Socket socket) {
super("RelayMultiClient");
this.socket = socket;
}
public void run() {
try {
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
if(Relay.max_clients == Relay.connected_clients) {
//There are too many clients on the server.
System.out.println("Connection refused from " + socket.getRemoteSocketAddress() + ": Too many clients connected!");
out.close();
in.close();
socket.close();
}
else {
Ini ini = new Ini(new File("settings.ini"));
Relay.connected_clients++;
System.out.println("Connection from client " + socket.getRemoteSocketAddress() + " established. Clients Connected: " + Relay.connected_clients);
while (in.readLine() != null) {
//Send data to the server
//Receive data from server and send back to client
}
System.out.println("Connection from client " + socket.getRemoteSocketAddress() + " lost.");
Relay.connected_clients--;
out.close();
in.close();
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Thanks,
Chris
P.S: I'm not attempting to get HTTP data, I am trying to get data from a game I have created. I don't know if this type of data requires any extra handling.
How could I incorporate elements to send data to the server, and send the response back to the client?
Try the following example as basic proxy:
public class Proxy {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(1230); // proxy port
Socket socket = serverSocket.accept();
Socket relay = new Socket("localhost", 1234); // server address
new ProxyThread(relay.getInputStream(), socket.getOutputStream()).start();
new ProxyThread(socket.getInputStream(), relay.getOutputStream()).start();
}
}
class ProxyThread extends Thread {
private InputStream inputStream;
private OutputStream outputStream;
ProxyThread(InputStream inputStream, OutputStream outputStream) {
this.inputStream = inputStream;
this.outputStream = outputStream;
}
public void run() {
try {
int i;
while ((i = inputStream.read()) != -1) {
outputStream.write(i);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
It lacks proper exception handling, only demonstrating the basic idea.
Related
as a part of my homework I have to build two classes one listener and one that is making the requests to the server (the server is already written by my teacher and I don't know how code looks like). In theory: The server that I'm connected to should reply with the exact same requests I sent to him. But in practice I get nothing back.
public class Listenerthread extends Thread {
Socket s;
Scanner answerServer;
public Listenerthread(Socket socket) {
this.s = socket;
this.answerServer = new Scanner(new BufferedReader(new InputStreamReader(s.getInputStream())));
}
public void run() {
System.out.println("Listening to the responses from the server......");
while (true) {
if (answerServer.hasNext()) {
System.out.println(answerServer.nextLine());
}
}
}
}
public class Mainthread {
public static void main(String[] args) throws ParseException {
Socket s = new Socket("someServer", 9999);
Listenerthread server = new Listenerthread(s);
server.start();
if (s.isConnected()) {
System.out.println("Connected");
}
String req = "Heyyy mate"; // server should sent me this back
PrintWriter pw = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
pw.println(req);
pw.flush();
//pw.close();
//s.close();
}
}
Update: A comment that OP left on the question after I started writing this answer shows that OP does not actually need to handle the server side of the communications. I will leave this answer for now in case it could still be useful.
When you have a client/server model, you should use a ServerSocket on the server side, as you alluded to in your question but then do not appear to have done in your code.
ServerSocket
Here is a ServerSocket example that may clear that up.
ServerSocket serverSocket;
public void serverSocketTest()
{
serverSocket = new ServerSocket(9999);
// each of the below methods will happen on separate threads
new Thread(this::serverSideAcceptConnectionFromClient).start();
new Thread(this::clientSideConnectToServer).start();
}
public void clientSideConnectToServer()
{
try {
System.out.println("Client is trying to connect to server...");
Socket connectionToServer = new Socket("localhost", 9999);
OutputStream thisGoesToTheServer = connectionToServer.getOutputStream();
InputStream thisIsDataComingFromServer = connectionToServer.getInputStream();
System.out.println("Client successfully connected to server.");
} catch(IOException ex) {
System.out.println("Connection to server failed. (" + ex + ")");
}
}
public void serverSideAcceptConnectionFromClient()
{
try {
System.out.println("Server is listening for potential clients...");
Socket connectionFromClient = serverSocket.accept();
InputStream thisIsDataComingFromClient = connectionFromClient.getInputStream();
OutputStream thisIsGoesBackOutToClient = connectionFromClient.getOutputStream();
System.out.println("Server accepted a client");
} catch(IOException ex) {
System.out.println("Error while listening for clients. (" + ex + ")");
}
}
I have my server code below over here:
public void startServer() {
ServerSocket listener = selectUnusedPortFromRange(1024, 65535);
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
String command = null;
while (true) {
Socket socket = listener.accept();
System.out.println("Got a connection from: " + socket.getLocalPort());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
command = in.readLine();
System.out.println("GOT HERE"); //Not being printed out
if (command != null && !"".equals(command)) {
if ("connection".equals(command)) {
Writer writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.write("success\n");
writer.flush();
}
}
}
}
}
}
t.start();
}
This is my client side:
public void makeConnection() {
try {
Socket socket = new Socket(IP, PORT);
Writer writer = new PrintWriter(socket.getOutputStream(), true);
writer.write("connection\n");
BufferedReader socketRead = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str;
while ((str = socketRead.readLine()) != null) {
if ("success".equals(str)) {
System.out.println("Successfully saved all hosts to: " + listOfHosts.get(i));
socketRead.close();
socket.close();
iStream.close();
writer.close();
}
}
}catch (Exception e) {
System.out.println(e.getMessage());
}
}
On the client side after I create my socket to the connect to the server I write "connection" into the outputStream of the socket and wait for an acknowledgement back from the server saying success. For some reason the connection is not being made to the server. In the server System.out.println("Got a connection from: " + socket.getLocalPort()); this line is not being printed out.
Is there something wrong that I am doing. I can't spot it. And I am not getting an exception thrown when I try to connect to my server.
1) Make sure you use the same port for both the Client and Server. They must communicate over the same port. It seems you may be using different ports currently.
2) Make sure you actually start your server thread. As-is in your code above, you make a new Thread, but never start it. t.start() must be called somewhere.
3) If this is on your local machine, you may be better off using localhost instead of the actual IP address. Firewalls might treat your external IP differently.
4) Terminate your messages with a newline character, such as \n, so that your BufferedReader can use it's readLine() method. For good measure, also follow-up by flushing the writer's buffer, just in case the newline character didn't trigger that. writer.flush();
And lastly, make sure you terminate the JVM before trying to run your code again. Your code has not shutdown mechanism to un-bind the server from the port... so you may get an exception thrown telling you the port and/or address are already in use. If that happens, either change ports, or kill the java process running in the background.
Here is your code, slightly modified to run on my system. It's working as you might expect it to. I tried to change as little as possible just to get it working on my system. One note is, I hard-coded the port number into the server and client - that's not required, it was just convenient for me to test with:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;
public class Test {
public static void main(String[] args) throws IOException {
Test test = new Test();
test.startServer();
test.makeConnection();
}
public void startServer() throws IOException {
final ServerSocket listener = new ServerSocket(60001);
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
String command = null;
while (true) {
Socket socket = listener.accept();
System.out.println("Got a connection from: " + socket.getLocalPort());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
command = in.readLine();
System.out.println("GOT HERE");
if (command != null && !"".equals(command)) {
if ("connection".equals(command)) {
Writer writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.write("success\n");
writer.flush();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
t.start();
}
public void makeConnection() {
System.out.println("Making Connection");;
try {
Socket socket = new Socket("localhost", 60001);
Writer writer = new PrintWriter(socket.getOutputStream(), true);
writer.write("connection\n");
writer.flush();
BufferedReader socketRead = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str;
while ((str = socketRead.readLine()) != null) {
if ("success".equals(str)) {
System.out.println("Successfully saved all hosts to: "); //+ listOfHosts.get(i));
socketRead.close();
socket.close();
//iStream.close();
writer.close();
}
}
}catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
I was facing the exact same issue. I overcame it by using an ACK mechanism (Wasn't my idea, it was suggested to me). The idea is that client would make a request to server and keep the socket connection alive (and the ouput stream open) till server responds back an agreed ACK message over the same channel. Once the client receives the ACK message, only then it would close the connection.
Below is the code for Server :-
final ServerSocket listener = new ServerSocket(11111);
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
String command = null;
while (true) {
System.out.println("About to accept");
Socket socket = listener.accept();
System.out.println("Got a connection from: " + socket.getLocalPort());
DataInputStream inputStream = new DataInputStream(socket.getInputStream());
StringBuilder str = new StringBuilder(inputStream.readUTF());
//command = in.readLine();
System.out.println("GOT HERE. Msg received : "+str);
if (str != null && !"".equals(str.toString())) {
command = str.toString();
if ("connection".equals(command)) {
System.out.println("Got connection message");
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
outputStream.writeUTF("connection");
outputStream.close();
}
}
inputStream.close();
System.out.println("Done");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
});
t.start();
}
Client :-
public void makeConnection() {
try {
System.out.println("In makeConnection");
Socket socket = new Socket("127.0.0.1", 11111);
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
outputStream.writeUTF("connection");
InputStream inputStream = socket.getInputStream();
DataInputStream dataInputStream = new DataInputStream(inputStream);
StringBuilder str;
do {
str = new StringBuilder(dataInputStream.readUTF());
} while (!str.toString().equals("connection"));
System.out.println("Successfully saved all hosts to: ");
outputStream.close();
dataInputStream.close();
socket.close();
outputStream.close();
}catch (Exception e) {
System.out.println(e.getMessage());
}
}
A call to start the proceedings :-
public void start() throws IOException, InterruptedException {
System.out.println("Starting server");
startServer();
Thread.sleep(1000);
System.out.println("Starting connection");
makeConnection();
}
I want to write a socket client to send a request to a server and get response back. It works, but not right.
Here is my code:
public String send(final String data) {
Socket client = null;
String response = null;
try {
client = new Socket(this.host, this.port);
final OutputStream outToServer = client.getOutputStream();
final DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF(data);
final InputStream inFromServer = client.getInputStream();
final DataInputStream in = new DataInputStream(inFromServer);
response = in.readUTF();
} catch (final IOException e) {
this.log.error(e);
this.log.error("Sending message to server " + this.host + ":" + this.port + " fail", e);
} finally {
if (client != null) {
try {
client.close();
} catch (final IOException e) {
this.log.error("Can't close socket connection to " + this.host + ":" + this.port, e);
}
}
}
if (StringUtils.isBlank(response)) return null;
return response;
}
The problem is: I didn't got the full response with in.readUTF(). I always got a response with the same length as the sent data's length (variable data). I have tested with other GUI client and got the full response. So it's not a problem of the server.
Does someone known, what i did wrong?
UPDATE
Thanks EJP and Andrey Lebedenko. I think, my problems are the functions writeUTF and readUTF. So i have edited my code in the try block so:
Charset charset = Charset.forName("ISO-8859-1");
final OutputStream outToServer = client.getOutputStream();
final DataOutputStream out = new DataOutputStream(outToServer);
out.write(data.getBytes(charset));
final InputStream inFromServer = client.getInputStream();
final BufferedReader in = new BufferedReader(new InputStreamReader(inFromServer, charset));
response = in.readLine();
And it worked now.
If it works with Telnet, as per your comment, the server isn't using readUTF(), so your writeUTF() is already wrong, and the server is therefore unlikely to be using writeUTF() either, which would make your readUTF() wrong as well. You can't use these methods arbitrarily: they can only interchange data between themselves.
I'll bet your GUI client that works doesn't use them either.
Without knowing what does server part do, it is kind of difficult (if possible at all) to trace down the root cause. So in the most honest hope that it will help I just share this code with which I've tested the fragment above.
package tcpsendreceive;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class SendReceive {
private static final Logger log = Logger.getLogger(SendReceive.class.toString());
private final String host;
private final int port;
private Server server;
class Server extends Thread
{
private final ServerSocket serverSocket;
public Server(ServerSocket s)
{
serverSocket = s;
}
#Override
public void run()
{
Socket connection;
SendReceive.this.log.log(Level.INFO, "Server: DoubleEcho Server running on "+this.serverSocket.getLocalPort());
try{
do {
connection = this.serverSocket.accept();
SendReceive.this.log.log(Level.INFO, "Server: new connection from "+connection.getRemoteSocketAddress());
int b;
do {
DataInputStream in = new DataInputStream(connection.getInputStream());
String s = in.readUTF();
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeUTF(s+","+s); // echo it back TWICE
out.flush();
connection.shutdownOutput();
connection.close();
} while(!connection.isClosed());
}
while(true);
}
catch(IOException ioe)
{
SendReceive.this.log.log(Level.SEVERE, "IOException in server! - STOP", ioe);
}
finally {
try{
this.serverSocket.close();
} catch (Exception e) {
SendReceive.this.log.log(Level.SEVERE, "IOException closing server! - FATAL", e);
}
try{
if(!connection.isClosed())
connection.close();
} catch (Exception e) {
SendReceive.this.log.log(Level.SEVERE, "IOException closing server! - FATAL", e);
}
}
}
}
public SendReceive(String host, int port)
{
this.host = host;
this.port = port;
try{
this.server = new Server(new ServerSocket(this.port));
this.server.start();
}
catch(IOException ioe)
{
this.log.log(Level.SEVERE, "IOException while creating server! - STOP", ioe);
}
}
public String send(final String data) {
Socket client = null;
String response = null;
try {
client = new Socket(this.host, this.port);
final OutputStream outToServer = client.getOutputStream();
final DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF(data);
final InputStream inFromServer = client.getInputStream();
final DataInputStream in = new DataInputStream(inFromServer);
response = in.readUTF();
} catch (final IOException e) {
this.log.log(Level.SEVERE, "Sending message to server " + this.host + ":" + this.port + " fail", e);
} finally {
if (client != null) {
try {
client.close();
} catch (final IOException e) {
this.log.log(Level.SEVERE, "Can't close socket connection to " + this.host + ":" + this.port, e);
}
}
}
if(response == null || response.isEmpty())
return null;
return response;
}
}
Test-demo
package tcpsendreceive;
public class Main {
public static void main(String[] args)
{
String data = "AAABBB";
SendReceive sr = new SendReceive("localhost", 5000);
String res = sr.send(data);
System.out.println("Sent: "+data);
System.out.println("Received: "+res);
}
}
Result (key part):
Sent: AAABBB
Received: AAABBB,AAABBB
Hope it helps.
EDIT
1. Corrected wrapper flush instead of socket stream flush. Still believe it is good practice to flush the stream wrapper before closing the socket.
Client socket closed in IOException block (since they aren't automatically closed on ServerSocket shutdown). Thanks #EJP
P.s. I should admit I was bit surprised by such an attention to the humble test server code, especially compared to other dirty tests we all have seen on SO. Flattered. :)
I have a client class and a server class.
If client sends message to server, server will send response back to the client, then client will print all the messages it received.
For example,
If Client sends "A" to Server, then Server will send response to client
"1111". So I use readLine() in client class to read the message from server, then client print "1111" in the console.
If Client sends "B" to Server, then Server will send response to client
"2222\n 3333". So the expected printing output from client is:
"2222"
"3333"
So the response message from server to client may have 1 line or 2 lines depending on the message it send from client to server.
My question is that how I can use readLine() to read the message that send from server to client. More specifically, if I use the following codes,
String messageFromServer;
while(( messageFromServer = inputStreamFromServer.readLine()) != null) {
println(messageFromServer);
}
It will only print the first line, and will not print anything else even if I keep sending message from client to server, because readLine() will stops once it has read the first line.
update:
More specifically, I am looking for some methods in the client class to read message that contains 1 or multiple lines from server at a time. I am wondering if there are any ways to do it in client side if I don't want to change the format of the message that sent from server to client.
update 2
To make my question more clear, I will put some sample codes in the following:
This is server:
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(1234);
} catch (IOException e) {
System.err.println("Could not listen on port: 1234.");
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
}
System.out.println("Connected");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String textFromClient =null;
String textToClient =null;
textFromClient = in.readLine(); // read the text from client
if( textFromClient.equals("A")){
textToClient = "1111";
}else if ( textFromClient.equals("B")){
textToClient = "2222\r\n3333";
}
out.print(textToClient + "\r\n"); // send the response to client
out.flush();
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
The client:
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
try {
socket = new Socket("localhost", 1234);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host");
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection");
}
System.out.println("Connected");
String textToServer;
while((textToServer = read.readLine())!=null){
out.print(textToServer + "\r\n" ); // send to server
out.flush();
String messageFromServer =null;
while(( messageFromServer = textToServer=in.readLine()) != null){
System.out.println(messageFromServer);
}
}
out.close();
in.close();
read.close();
socket.close();
}
private static void debug(String msg)
{
System.out.println("Client: " + msg);
}
}
You shouldn't need to change the format of the data sent by the server, and readLine() should work, but I suspect that the server is not flushing or closing the OutputStream after writing the response which could possibly explain things.
Is the call to readLine() hanging? Are you in control of the server code? If so, can you include it?
Revised classes that work as I believe you expect:
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 ClientServerTest2
{
public static void main(String[] args) throws Exception
{
Thread serverThread = new Thread(new Server());
serverThread.start();
Thread clientThread = new Thread(new Client());
clientThread.start();
serverThread.join();
clientThread.join();
}
private static class Server implements Runnable
{
#Override
public void run()
{
ServerSocket serverSocket = null;
try
{
serverSocket = new ServerSocket(1234);
Socket clientSocket = null;
clientSocket = serverSocket.accept();
debug("Connected");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String textFromClient = null;
String textToClient = null;
textFromClient = in.readLine(); // read the text from client
debug("Read '" + textFromClient + "'");
if ("A".equals(textFromClient))
{
textToClient = "1111";
}
else if ("B".equals(textFromClient))
{
textToClient = "2222\r\n3333";
}
debug("Writing '" + textToClient + "'");
out.print(textToClient + "\r\n"); // send the response to client
out.flush();
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
private static void debug(String msg)
{
System.out.println("Server: " + msg);
}
}
private static class Client implements Runnable
{
#Override
public void run()
{
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
try
{
socket = new Socket("localhost", 1234);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
debug("Connected");
String textToServer;
textToServer = read.readLine();
debug("Sending '" + textToServer + "'");
out.print(textToServer + "\r\n"); // send to server
out.flush();
String serverResponse = null;
while ((serverResponse = in.readLine()) != null)
debug(serverResponse); // read from server and print it.
out.close();
in.close();
read.close();
socket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
private static void debug(String msg)
{
System.out.println("Client: " + msg);
}
}
Change while(( messageFromServer = inputStreamFromServer.readLine() != null) to while(( messageFromServer = inputStreamFromServer.readLine()) != null)
Actually this shouldn't even compile....
It's a work around.
If you want to send multiple strings like in your case : "2222\n 3333".
You can send them by adding a seperator character (like :) between two strings : "2222: 3333".
Then you can call write from server side as
clientOut.write("2222: 3333\n");
On client side parse recieved String :
messageFromServer = inputStreamFromServer.readLine();
String strArray[] = messageFromServer.split(":");
strArray[0] : 2222
strArray[0] : 3333
I have the following Situation.
I have a Server class.
I have a Client class.
I have a MultiServerThread class.
When a Client connects to a Server, the Server creates a new MultiServerThread, which is processing the Input from the Client. That way I can have multiple Clients. So far so good.
The connection goes via TCP.
A short example:
Server class:
...
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
boolean listening = true;
try {
serverSocket = new ServerSocket(9999);
} catch (IOException e) {
System.err.println("Could not listen on port: " + serverSocket.getLocalPort() + ".");
System.exit(-1);
}
while (listening) {
new MultiServerThread(serverSocket.accept()).start();
}
serverSocket.close();
}
...
Client class:
...
public static void main(String[] args) throws IOException {
socket = new Socket(hostname, port);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String 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();
socket.close();
}
...
MultiServerThread class:
...
public MultiServerThread(Socket socket) throws SocketException {
super("MultiServerThread");
this.socket = socket;
// dSocket = new DatagramSocket(4445);
}
public void run() {
try {
PrintWriter myOutput = new PrintWriter(socket.getOutputStream(), true);
BufferedReader myInput = new BufferedReader(new InputStreamReader(socket.getInputStream()));
myOutput.println("Connected to client and ready to accept commands.");
while ((clientInput = myInput.readLine()) != null) {
//A SIMPLE LOGIN A USER
if (clientInput.contains("!login")) {
//save some string given by client into loggedUser
String loggedUser = clientInput.substring(7);
}
myOutput.close();
myInput.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
What I need is:
I need to implement a notification that comes from a Server when for example the Username is "Bob". If the username is "Bob", the server should give a notification to the Client "Bob is here again!". In my project/homework this should be done with datagrams in Java.
So if the clientinput is "!login bob" then a datagram packet with the message ("Bob is here again!") should be sent to the client.
Question: Where exactly should I put the code of the Datagram request in? Can I put the datagram packet request into the MultiServerThread or into the Client?
It would be easier in the MultiServerThread because it already handles the !login.
Here:
if (clientInput.contains("!login")) {
//save some string given by client into loggedUser
String loggedUser = clientInput.substring(7);
//send datagram request to Server???
}
But this is going against the principle of networking?
you need to send the UDP port number to your client through the initial TCP connection. Then you start listening for UDP datagrams on your client on that port number. All other communications from server -> client will be on this udp socket. This is what your assignment suggests
I got it working ;-)
I definied a udp port in the thread and client class...
the client class got his port with arguments... it gave the udp Port to the thread... so both had the udp ports ;)