Java Send array of processes via tcp to server - java

I am programming a external Taskmanager and i need to send the process list via tcp to my server application. But i don't know how to start and how this works.
Edit:
I have the processlist i only have to send it via TCP to the Serverside.
Thx for your help.

If you already have a processlist, then it's not so hard to make client-server logic for your purposes with Java. First of all, you need to make a server side:
public class ServerSide {
public static void main(String[] args) {
try
{
ServerSocket myServerSocket = new ServerSocket(9999);
Socket skt = myServerSocket.accept();
List<Process> objects = null;
try {
ObjectInputStream objectInput = new ObjectInputStream(skt.getInputStream());
try {
Object object = objectInput.readObject();
objects = (ArrayList<Process>) object;
System.out.println(objects);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Wich will use a ServerSocket to listen on specified port, in this case is 9999. Then connection accepted (take a look at myServerSocket.accept(), it stops the execution, until any connection is accepted), it creates a Socket and you can get it's InputStream and get an object from it. In this example server stops after first accepted connection, you should make it accept any number of connections with infinity loop for example.
When you have a server, you can make a client side, which will send a list of Processes to the Server:
public class ClientSide {
public static void main(String[] args) {
try {
Socket socket = new Socket("127.0.0.1",9999);
ArrayList<Process> my = new ArrayList<Process>();
my.add(new Process("Test1"));
my.add(new Process("Test2"));
try
{
ObjectOutputStream objectOutput = new ObjectOutputStream(socket.getOutputStream());
objectOutput.writeObject(my);
}
catch (IOException e)
{
e.printStackTrace();
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In this case, you'll create a Socket by youself, give an eddress and port number to it, where it will send a data. Then you can get an OutputStream and pass your data through it. In example above, you pass an Array of Process object instances. The Process class looks like:
public class Process implements Serializable {
private String processName = null;
public Process(String processName) {
this.processName = processName;
}
#Override
public String toString() {
return processName;
}
}
The main thing in case of Process class, it should implement the Serializable interface. In that case, you don't need to make some logic for it's serialization.
But if you have to make a client with Java, but not a server, then it could be a little bit harder. You may take a look here, to see some kind of example, how Java-client communicates with C++ server. Anyway, in Java-part you should use a Socket and it's OutputStream, only the data representation will differ.

Related

what happens to a message when it gets to a server without reading stream in java?

If I have a server and a client and I opened a socket between the two:
1.Is it possible that the client will have a printWriter stream, in order to write things to the socket, but the server won't have in the mean time a bufferReader?
If the answer of 1 is yes, if that client will send a message to the server (who currently doesn't have a reading stream), what will happend to this message until te server will create a reading stream and read the message?
thank you
This is not at all specific to Java, but TCP/IP. There are buffers to keep the data received, so it's not possible that some data would be lost because one end isn't "ready" yet. This is because TCP will retransmit data that hasn't been acknowledged as received, guaranteeing that all the bytes that are written are received on the other (barring obvious cases).
in addition to #Kayaman's answer:
consider this Compile-able simple Java implemented example:
Server Side:
import java.io.*;
import java.net.*;
public class SimpleServer implements Runnable{
int serverPort = 45000;
ServerSocket serverSocket = null;
boolean isStopped = false;
public SimpleServer(int port){
this.serverPort = port;
}
public void run(){
try {
serverSocket = new ServerSocket(serverPort);
} catch (IOException e) {
System.err.println("Cannot listen on this port.\n" + e.getMessage());
System.exit(1);
}
while(!isStopped){
try {
Socket clientSocket = serverSocket.accept();
} catch (IOException e) {
// do nothing
}
}
}
public static void main(String[] args) throws IOException {
SimpleServer server = new SimpleServer(45000);
new Thread(server).start();
System.out.println("Server is waiting to connect");
}
}
Client Side:
import java.io.*;
import java.net.*;
public class SimpleClient {
public static void main(String[] args) throws IOException {
Socket socket = null;
PrintWriter out = null;
try {
socket = new Socket("127.0.0.1", 45000);
out = new PrintWriter(socket.getOutputStream(), true);
System.out.println("output stream created");
out.write(9);
System.out.println("message was sent to output with no listener");
} catch (UnknownHostException e) {
// do nothing
} catch (IOException e) {
// do nothing
}
}
}
the example is an implementation of a very basic client server connection in which a socket is created and a stream is defined only on the client side, followed by a write to the stream that will eventually be read by the server (if at all).
therefore, to answer you questions:
1) yes, it's possible to open a one-way connection stream without a "listener"
2) edit: according to #EJP: It will be saved within the socket's buffer until it is read or the socket is closed.

Java Server producing inconsistent output

I want to integrate a server with multiple clients for a blackjack game I created, and thus I began practicing with servers in java. I create a thread, that when ran, forces the server to listen for input and produce an output. Then I added a feature to stop the server. However, the server randomly produces the correct output, and sometimes fails to connect. Here is the code for when the user hosts a server:
st = new ServerThread(); //this is a field of type ServerThread
st.start(); //this runs the server concurrently as a new thread
Here is the code for when they close a server:
st.stopThread();
Finally, here is the source for the serverThread:
public class ServerThread extends Thread {
private volatile boolean isRunning = true;
private Socket socket;
private static final int PORTNUM = 1342;
#Override
public void run() {
while (isRunning) { //should run only when the
try {
ServerSocket serverSocket = new ServerSocket(PORTNUM); //uses the same port number, which I made a constant
//Reading the an object of type Information from the client
socket = serverSocket.accept();
ObjectInputStream serverInputStream = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream serverOutputStream = new ObjectOutputStream(socket.getOutputStream());
Information i = (Information) serverInputStream.readObject();
//arbitrarily changes the data stored in the information object to verify connection with server
i.setI(100);
i.setS("new string");
i.setD(4.4);
//sends the modified object back to the client
serverOutputStream.writeObject(i);
serverInputStream.close();
serverOutputStream.close();
socket.close();
} catch (IOException e) {
//System.out.println("IOException");
//e.printStackTrace();
} catch (ClassNotFoundException e) {
//System.out.println("ClassNotFoundException");
//e.printStackTrace();
} finally {
try {
if (socket != null) { //avoid null pointer if no connections have been established
socket.close();
}
} catch (IOException ex) {
//Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public void stopThread() {
isRunning = false;
}
}
Any suggestions on edits to make my code perform correctly and consistently would be welcome. Thanks.
I would move the socket definition away from being an instance variable i.e,
while (isRunning) {
Socket socket = null;
try {
...

how can i send data to the selected client from server?

i'm building a multithread example using sockets and threads in java. the sever will get multiple Socket at same time, and when i send a message from server, i want the socket from client to go back in order to what i give.
my understanding so far is to make ArrayList but i have no idea how to use it for my purpose.
can anyone help or give me any clue to solve this problem?
following is the code:
//server socket to wait before accepting from client.
public class ServerSocketEntry {
ServerSocket ssoc;
Socket soc;
ArrayList<Socket> arrSocket = new ArrayList<Socket>();
private static final int port=4853;
public ServerSocketEntry(ServerManagement sm){
try {
ssoc = new ServerSocket(port);
System.out.println("Waiting");
while(true){
soc=ssoc.accept();
arrSocket.add(soc);
System.out.println("Accepted: "+soc);
ServerSocketThread sth = new ServerSocketThread(soc,sm);
sth.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ServerManagement sm = new ServerManagement();
new ServerSocketEntry(sm);
}
}
//threadClass using readObject(), writeObject() method.
public class ServerSocketThread extends Thread {
Socket soc;
ObjectOutputStream oos;
ObjectInputStream ois;
ServerManagement sm;
Food food;
public ServerSocketThread(Socket soc,ServerManagement sm) {
this.soc=soc;
this.sm=sm;
try {
ois= new ObjectInputStream(soc.getInputStream());
oos= new ObjectOutputStream(soc.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
public void run(){
Command com;
while(true){
try {
com = (Command) ois.readObject();
if(com.getCommand()==Command.Member_Check){
Member member = (Member) com.getObj();
System.out.println("thread: "+member);
if(sm.checkMember(member)){
com.setCommand(Command.Command_OK);
}else{
com.setCommand(Command.Command_Fail);
}
}else if(com.getCommand()==Command.LogIn_Check){
Member member = (Member) com.getObj();
if(sm.checkLogIn(member)){
com.setCommand(Command.Command_OK);
}else{
com.setCommand(Command.Command_Fail);
}
}else if(com.getCommand()==Command.Food_Check){
ArrayList<Food> serverArrFood = com.getFoodOrder();
if(sm.checkFood(serverArrFood)){
com.setCommand(Command.Command_OK);
}else{
com.setCommand(Command.Command_Fail);
}
}
oos.writeObject(com);
oos.flush();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Then you may use a hash map to store the connected clients and it will be easy to get a specific client from the map and send message to that. Use a nickname of the client as the key and socket as a value at the time when a new client connects to the sever. Put these values into the map. For Example:
Map<String, Socket> clients = new HashMap();
clients.put(nickname, clientSocket);
While writing simply get that specific client by its key.
clients.get(nickname);
and write to its output stream. When one client sends message to a specific client, it should send the receiver's nickname as part of the message to the server.

Java TCP sockets, sending and receiving objects in a thread

I'm a a beginner programmer, currently stuck on a java project. I have a fully working singleplayer minesweeper game, object-oriented, and I'm trying to implement a TCP multiplayer function. The game has a control class, which handles the view, game field, timer, labels, has the action listeners, etc.
For multiplayer, I'm trying to make a separate thread, which has the Socker and the ServerSocket, and depending on the parameters passed on by the constructor, acts as a host or client. While running, it should be trying to read my custom Packet class from the input stream, and another method can send packets. Here is the code:
public class MultiThread extends Thread {
GameControl gc;
ServerSocket servSocket;
Socket socket;
Packet data;
ObjectInputStream incoming;
ObjectOutputStream outgoing;
Boolean isHost;
Boolean commEnd;
public MultiThread(GameControl gc, Boolean isHost) {
this.gc = gc;
this.isHost = isHost;
this.commEnd = false;
gc.chatDialog.setVisible(true);
}
public void run() {
try {
if (isHost) {
servSocket = new ServerSocket(1234);
gc.chatDialog.status.setText("Awaiting connection...");
socket = servSocket.accept();
gc.chatDialog.status.setText("Connected.");
incoming = new ObjectInputStream(socket.getInputStream());
outgoing = new ObjectOutputStream(socket.getOutputStream());
}
else if (!isHost){
socket = new Socket("localhost", 1234);
if (socket.isConnected()) {
gc.chatDialog.status.setText("Connected.");
incoming = new ObjectInputStream(socket.getInputStream());
outgoing = new ObjectOutputStream(socket.getOutputStream());
}
else {
gc.chatDialog.status.setText("No connection.");
}
}
while (!commEnd) {
try {
Thread.sleep(100);
data = (Packet)incoming.readObject();
System.out.println(data.msg);
gc.chatDialog.chatArea.append(data.getMsg());
}
catch (IOException e) {e.printStackTrace();}
}
System.out.println("asd");
gc.chatDialog.status.setText("No connection");
incoming.close();
outgoing.close();
socket.close();
servSocket.close();
}
catch (Exception e) {e.printStackTrace();}
}
public void sendPacket(Packet p) {
try {
outgoing.writeObject(p);
}
catch (IOException e) {e.printStackTrace();}
}
}
The connection gets established on localhost, but I'm getting an exception thrown when trying to initialize the incoming and outgoing fields.
Sorry if the code is a mess, I get the feeling I'm in some serious misunderstanding, so any help is appreciated.

serversocket server + client issues

ok is hard for me to describe my problem now but then i will try my best to in order for me to get some assist.
technically i have a server.java and client.java as a super class. and my layout structure for my server and client connection goes like this
MAIN SERVER --- CLIENT/SERVER ----- CLIENT
my main problem is the this CLIENT/SERVER part is 1 driver class that calls 2 different classes which is CLIENT and SERVER together... and this creates a problem when my CLIENT sends something that needs to be received by MAIN SERVER side needs to go through CLIENT/SERVER part. if is that condition happens..
the CLIENT of course need to interact with CLIENT/SERVER (SERVER) part because is a SERVER that accepts the CLIENT data. but now i wanted the (SERVER) part in the CLIENT/SERVER to transfer the data to (CLIENT) in the CLIENT/SERVER part so that it can be send to the MAIN SERVER
how is it possible for me to write something that allows the CLIENT/SERVER to interact with each other so it can transfer the data between them vise versa? how ever this is my code for calling the CLIENT and SERVER together
public class Slave {
public static void main(String args []) throws IOException{
try{
// set Config file settings to slave mode
Config cfg = new Config("Slave");
String MasterServerIP = cfg.getProperty("ServerIP");
String MasterServerPort = cfg.getProperty("ServerPort");
String SlaveServerPort = cfg.getProperty("ListeningPort");
System.out.println("Slave Client connecting to Master Server");
// start connect to master server by calling the SlaveClient class
new SlaveClient(MasterServerIP,Integer.parseInt(MasterServerPort)).start();
int numClient = 0;
ServerSocket listener = new ServerSocket(Integer.parseInt(SlaveServerPort));
System.out.println("Server starts running");
try{
while(true){
// start listening to the server port by calling SlaveServer class
new SlaveServer(listener.accept(), numClient++, Integer.parseInt(SlaveServerPort)).start();
}
} finally {
listener.close();
}
} catch (FileNotFoundException file) {
System.out.println("File Not Found Error: "+file.getMessage());
}
}
}
the above is only the driver class that calls the 2 object class which is the SERVER and CLIENT side.
i will attach my slaveserver and slaveclient code here but i am not sure how to do it like you said
public class SlaveServer extends Server {
private JFrame frame = new JFrame();
private JTextArea msgArea = new JTextArea();
private JTextArea connectionArea = new JTextArea();
// SlaveServer Constructor
public SlaveServer(Socket socket, int numClient, int port) {
super(socket, numClient, port);
}
public void writeToMsg(String msg){
msgArea.append(msg+"\n");
}
public void writeToConnection(String msg){
connectionArea.append(msg+"\n");
}
public void run(){
try{
startGUI();
// initial BufferedReader and PrintWriter object by binding it with Socket
BufferedReader in = new BufferedReader(new InputStreamReader(getSocket().getInputStream()));
PrintWriter out = new PrintWriter(getSocket().getOutputStream(), true);
// welcome message send from server to client
out.println("Welcome to the Slave Server port:"+getPort()+" client #"+getNumClient());
while(true){
String readmsg = in.readLine();
writeToMsg(readmsg);
}
} catch (IOException e){
writeToMsg("Error in closing Socket");
}
writeToConnection("Connection from client #"+getNumClient()+" is closed");
}
}
public class SlaveClient extends Client{
private BufferedReader in;
private PrintWriter out;
private JFrame frame = new JFrame();
private JTextArea msgArea = new JTextArea();
private JTextArea connectionArea = new JTextArea();
// SlaveClient Constructor
public SlaveClient(String ip, int port) {
super(ip, port);
}
public void run(){
startGUI();
Socket sock = null;
try {
sock = new Socket(getIp(), getPort());
} catch (IOException e) {
e.printStackTrace();
}
try {
in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
try {
out = new PrintWriter(sock.getOutputStream(), true);
} catch (IOException e) {
e.printStackTrace();
}
out.println("TEST");
// while loop for reading message from server
while(true){
try {
getMsg(in);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
So you are trying to write a proxy?
You you need to give the server half of the proxy a reference to the client half, so that it can forward the data.
Then create a method in the client half to accept messages from the server half.
So each message you read in at the server half, you pass to the client half. The client half can then pass it to the real server.

Categories

Resources