I am looking at the following documentation in hopes of understanding uniData. The problem that I am experiencing is that I am unable to make a "simulated real-like version" of a backend server inorder to test my unidata queries.
Here is what I have so far:
I have a main entry into the server, to listen:
public static void main(final String[] args) throws UnknownHostException, IOException {
int clientNumber = 0;
final ServerSocket listener = new ServerSocket(31438);
try {
while (true) {
new MySimulatedConnection(listener.accept(), clientNumber++).start();
}
} finally {
listener.close();
}
}
The SimulatedConnection receives requests, and attempts to read some data from them. (Purely using sockets)
#Override
public void run() {
try {
final BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
final PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
while (true) {
final String input = in.readLine();
if (input == null || input.equals(".")) {
break;
}
out.print("## received message " + input);
}
} catch (final IOException e) {
System.out.println("Error handling client# " + requestNumber + ": " + e.getMessage());
} finally {
try {
socket.close();
} catch (final IOException e) {
System.out.println("## cant close socket " + e.getMessage());
}
}
}
On my client, I am establishing a uniData session with something like this:
public static void main(final String[] args) throws UnknownHostException, IOException, UniSubroutineException,
UniSessionException {
final FakeClient faker = new FakeClient();
faker.createConnection();
}
private void createConnection() throws UnknownHostException, IOException, UniSubroutineException,
UniSessionException {
System.out.println("Connecting to unidata...");
UniSession uSession = new UniSession();
final UniJava uj = new UniJava();
uSession = uj.openSession();
uSession.setHostName("127.0.0.1");
uSession.setUserName("sample_username");
uSession.setPassword("sample_password");
uSession.setAccountPath("some_account");
uSession.setTimeout(5000);
final int port = uSession.connection.getPort();
System.out.println("Testing connection to " + SERVER_ADDRESS + " on port " + port + "...");
final Socket testSocket = new Socket(SERVER_ADDRESS, port);
if (testSocket.isConnected()) {
System.out.println("Connection successful");
uSession.connect();
System.out.println("## we performed the connect");
final UniSubroutine sub = uSession.subroutine("UNIJAVA.SETUP", 3);
sub.setArg(0, "unknwon host");
sub.call();
System.out.println("## sub called");
} else {
System.out.println("### no connection possbile!");
}
}
Why am I doing it the way I am?
Well, I am experimenting to see how I can create a server and how I can query for some data out of it. Obviously, my first choice is to use socketing as this seems to be the basic principle of communication here.
What is working, and what is not?
So far, the client is able to connect to the tcp socket, and read this line:
System.out.println("Connection successful");
However, connecting using uniApi, yeilds no success and a long timeout (since that is the way i configured it in the uSession.setTimeout(5000); value :
uSession.connect();
In addition, my buffered reader reads no data on the server, as I am guessing the subroutine paramaters I am passing are actually not being called as strings.
With that in mind, what am I trying to do?
I want to update my server to accept uniAPI requests, and act as an actual server that can perform some actions. However, it is obvious that I am missing in implementing possibly some interface, or some connection management, inorder to get this to work. Any idea as to what that may be?
Related
I am new at stackoverflow and I am sorry if this kind of a question is asked before but did a quick search and I could not find any title like mine. I am working on a multi-client chat application on Java. I was following the tutorials and I can send messages that every user in the application can see. But I wonder how to create and send a private message to a spesific user into the chat.
import java.io.*;
import java.net.*;
import java.util.HashSet;
import java.util.Set;
public class ChatServer {
private int port;
private Set<String> userNames = new HashSet<>();
private Set<UserThread> userThreads = new HashSet<>();
public ChatServer(int port) {
this.port = port;
}
public static void main(String[] args) {
new ChatServer(9999).execute();
}
private void execute() {
try {
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("Server is running");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("New user connected");
UserThread newUser = new UserThread(socket, this);
userThreads.add(newUser);
newUser.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void addUserName(String s) {
this.userNames.add(s);
}
public void broadcast(String serverMessage, UserThread excludeUser) {
for (UserThread aUser : userThreads) {
if (aUser != excludeUser)
aUser.sendMessage(serverMessage);
}
}
}
The code above is my server code.
public void run() {
Console console = System.console();
String userName = console.readLine("Enter your username : ");
writer.println(userName);
String text;
do {
text = console.readLine("[" + userName + "]: ");
if (text.startsWith("[")) {
isTargeted = true;
this.aimUserName = text.substring(text.indexOf("[") + 1, text.indexOf("]"));
//System.out.println("Private Message to: " + aimUserName);
} else {
isTargeted = false;
}
writer.println(text);
} while (!text.equals("bye"));
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and this code above is a part of my write thread class. As you can see, if a message starts with '[name]' part, the "name" means the user that we want to send a private message. By doing this, I can get the name of the user that I want to send a private message but I could not figure out how to broadcast this message just to that spesific user. I believe I need to configure my broadcast function in ChatServer class but I don't really know how to do. What steps should I follow?
--Edit--
I've been working on my question and I did some additions to solve my problem. First of all, I think I should share everything I have to you. I shared my ChatServer class previously. Other classes I have are:
import java.io.IOException;
import java.net.Socket;
public class ChatClient {
public static void main(String[] args) {
new ChatClient().execute();
}
private void execute() {
try {
Socket socket = new Socket("localhost", 3);
System.out.println("Connected to chat server");
new ReadThread(socket, this).start();
new WriteThread(socket, this).start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
import java.net.*;
import java.io.*;
public class ReadThread extends Thread{
private BufferedReader reader;
private Socket socket;
private ChatClient client;
public ReadThread(Socket socket, ChatClient client) {
this.socket = socket;
this.client = client;
InputStream input;
try {
input = this.socket.getInputStream();
this.reader = new BufferedReader(new InputStreamReader(input));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
while(true) {
try {
String response = this.reader.readLine();
System.out.println("\n" + response);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
break;
}
}
}
}
import java.net.Socket;
import java.io.*;
public class UserThread extends Thread {
private Socket socket;
private ChatServer server;
PrintWriter writer = null;
public String userName;
public UserThread(Socket socket, ChatServer chatServer) {
this.socket = socket;
this.server = chatServer;
}
public void run() {
try {
InputStream input = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
OutputStream output = socket.getOutputStream();
writer = new PrintWriter(output,true);
String userName = reader.readLine();
this.userName = userName;
server.addUserName(userName);
String serverMessage = "New user connected: " + userName;
server.broadcast(serverMessage,this);
String clientMessage;
do {
clientMessage = reader.readLine();
serverMessage = "[" + userName + "] : " + clientMessage;
server.broadcast(serverMessage, this);
}while(!clientMessage.equals("bye"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void sendMessage(String serverMessage) {
writer.println(serverMessage);
}
}
import java.net.*;
import java.io.*;
public class WriteThread extends Thread {
private Socket socket;
private ChatClient client;
private PrintWriter writer;
public WriteThread(Socket socket, ChatClient client) {
this.socket = socket;
this.client = client;
OutputStream output;
try {
output = socket.getOutputStream();
this.writer = new PrintWriter(output, true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
Console console = System.console();
String userName = console.readLine("Enter your username : ");
writer.println(userName);
String text;
do {
text = console.readLine("[" + userName + "]: ");
if(text.startsWith("[")){
String aimUserName = text.substring(text.indexOf("[")+1,text.indexOf("]"));
System.out.println("Private Message to: " + aimUserName);}
writer.println(text);
}while(!text.equals("bye"));
/*do {
text = console.readLine("[" + userName + "]: ");
writer.println(text);
}while(!text.equals("bye"));*/
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
These codes work properly and I can multi-chat very clean. But while working on private chat stuff, I added to the ChatServer the line of:
public void privatebr(String serverMessage, String targetUserName){
for(UserThread aUser: userThreads){
if(aUser.userName == targetUserName)
aUser.sendMessage(serverMessage);
}
to the UserThread, I edited the part as:
String clientMessage;
do {
clientMessage = reader.readLine();
serverMessage = "[" + userName + "] : " + clientMessage;
if(clientMessage.startsWith("[")){
String targetUserName = clientMessage.substring(clientMessage.indexOf("[")+1,clientMessage.indexOf("]"));
serverMessage = "[" + userName + "] : " + clientMessage;
server.privatebr(serverMessage, targetUserName);
}else{
server.broadcast(serverMessage, this);
}
}while(!clientMessage.equals("bye"));
But when I did all these edits, the normal multi-chat progress became broken where is my fault? Why everything has broken?
Good question! To answer the question you asked is that you should maintain a Map of Users to their Socket connections, so that way with DMs you can just select the user(s) that you want to message. You will also need a messaging protocol for that (see below)
...But I have to tell you that using Sockets and SocketServer classes in today's day and age is like re-inventing the wheel. The place to start in doing a chat server is using the web sockets protocol. Even under this, you will probably want to define a message protocol (like I did - I created a messaging protocol using JSON and message types, where the string message in the websocket event onMessage first gets parsed into an object)
There are implementations for supporting WS on all platforms: java, .net, python, php etc. This should be your starting point.
--- Update ---
I understand where you are coming from. To help you along in understanding Sockets / ServerSockets, here are a couple of pointers & resources
DatagramSockets (aka UDP): This is a different transmission protocol than the regular TCP, used by Shockwave and then Flash, and is the fundamental reason that Flash is problematic. I strongly recommend against this
Data & Object Input/OutputStreams: "Data" streams are Java only (can't connect to technologgy built on other platforms). Object streams are similar, except you are transporting actual whole objects through the stream (also Java only) No one* (almost no one) uses these anymore.
SocketException: Using java.net.[Server]Socket(s), you are likely to encounter this exception. It happens when you are waiting for more data (through a read / readLine call) on a socket, and the socket closes. It took me a long time to figure this out, but THIS EXCEPTION IS YOUR FRIEND! You get it when the connection has closed (either on the client or server side). It allows the thread that was waiting on the socket to wake up, and allows you to do whatever clean-up you need to do. SocketException is a subclass of IOException, so you may not even realize what this is. But now at least I have warned you
Streams vs. Writers and Readers: Writers and Readers are for interpreting raw bytes as Java characters and Strings. This is necessary, as there are multiple text formats (i.e. ascii, windows-xx, utf-8, utf-16). Readers and Writers help you read and write text in different text formats (and also interpreting Images from image formats).
Buffered Writers and Streams: These are for INEFFICIENT reading and writing. For writing, this means enabling you to write part of a message and not send it until you are ready. For reading, this means reading streams line by line for example rather than reading everything at one go.
TUS: tjacobs/io - https://sourceforge.net/p/tus/code/HEAD/tree/tjacobs/io/ this is an old collection of Java libraries I put on SourceForge years ago, but a lot of the classes here pertain to dealing with Sockets. In particular, see SocketServerEx, DataFetcher, Main/App, Timeout, and maybe IOUtils. And of everything, really look at DataFetcher which is a lightweight threadableframework for Callback I/O listening.
Good luck and have fun!
I'm programming a server in java that broadcasts the Date() function each second to the clients. The problem is that it worked for only one client but as soon as I started making modifications for multi-client support it broadcasts the Date() only once and then stops, as if the function is being called only once. I can not find what I'm doing wrong so I will just paste the code and hopefully someone will spot the mistake. I searched online but only to end up more confused than I started. For Client program I use the tellnet terminal app for windows.
public class Server
{
private ServerSocket SERVER;
private int PORT;
private Socket CLIENT;
public Server()
{
PORT = 8818;
try
{
SERVER = new ServerSocket(PORT);
System.out.println("Server started on port: " + PORT);
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
public void On() throws IOException
{
while(true)
{
CLIENT = SERVER.accept();
new ClientHandler(CLIENT).start();
}
}
}
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public class ClientHandler extends Thread
{
private Socket CLIENT;
private OutputStream out;
public ClientHandler(Socket CLIENT)
{
System.out.println("Accepted Connection from: " + CLIENT.getInetAddress());
this.CLIENT = CLIENT;
}
public void run()
{
try
{
out = CLIENT.getOutputStream();
out.write(("Time now is: " + new Date() + "\n").getBytes());
sleep(1000);
}
catch(Exception e)
{
System.out.println(CLIENT.getInetAddress() + " has left the session");
try
{
out.close();
CLIENT.close();
}
catch(IOException j)
{
System.out.println("Unexpected Error");
System.exit(-1);
}
}
}
}
Your modifications nearly worked - below is a running version with only minor modifications from your code.
A part of your modifications you unintentionally removed the while loop in the run function, which means the Date() function is in fact only called once. To see this, remove the while loop in run() and after the Date is printed (in the telnet window) the message "Done with the run function." is printed.
I added an identifier to each client which is printed with the date. The static cnt class field makes sure that each client has a different id.
I started separate clients in separate command prompt terminals using
telnet localhost 8818 such that they were running at the same time. At the bottom is the output from the 3rd client.
I did switch the code to camelCase convention (start variables with a lower case letter and capitalizing each new word) since all CAPS is usually reserved for constants and the change made the code easier to read for me.
public class Server
{
private ServerSocket server;
private int port;
private Socket client;
public Server()
{
port = 8818;
try
{
server = new ServerSocket(port);
System.out.println("Server started on port: " + port);
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
public void on() throws IOException
{
while(true)
{
client = server.accept();
new ClientHandler(client).start();
}
}
}
public class ClientHandler extends Thread {
private Socket client;
private OutputStream out;
private int id;
private static int cnt=0;
public ClientHandler(Socket client) {
System.out.println("Accepted Connection from: " + client.getInetAddress());
this.client = client;
id=cnt;
cnt++;
}
public void run() {
try {
out = client.getOutputStream();
while (true) {
out.write(("Client " + id + ": Time now is: " + new Date() + "\n").getBytes());
sleep(1000);
}
} catch (Exception e) {
System.out.println(client.getInetAddress() + " has left the session");
try {
out.close();
client.close();
} catch (IOException j) {
System.out.println("Unexpected Error");
System.exit(-1);
}
}
System.out.println("Done with the run function.");
}
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Server s = new Server();
s.on();
}
}
Explanation
I'm currently trying to create a Multiplayer Game with Java where up to five Players can play together.
The problem is that when I'm trying to connect multiple Clients to my Server I get an Exception and the Server doesn't work anymore.
With one Client at a time, everything works fine.
So what I need is a Server that can handle up to five players at a time and the clients should always get some new game data from the Server
every few seconds (Connected Players, etc.).
The "Game data" in the code below is the String I'm sending through the Object Stream.
Normally I would send an Object which has all the game data, but with the String, I get the same problem.
I'm struggling with the problem that only one Client can connect without any errors occurring for some days now and I didn't find a solution to my problem.
I saw that there are things like java.nio or the ExecutorService, but I didn't really understand those that much, so I don't know if they can help.
I have made a smaller program that simulates the same problem I get with my bigger program.
To Start the Server, you need to Start the GameMultiPlayerCreate.java Class, and for the Client, the Client.java class.
I'm new to Sockets so if something is unnecessary or if something can be made better please let me know.
So the Error I'm getting when I connect two or more Clients is:
java.io.StreamCorruptedException: invalid stream header: 00050131
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at Server.waitForData(Server.java:89) //I highlighted that in the code with a comment
at Server.loopWaitForData(Server.java:49)
at Server.run(Server.java:34)
at java.lang.Thread.run(Unknown Source)
Code
GameMultiPlayerCreate.java: Should start the Server threads if a Client connects
public class GameMultiPlayerCreate {
ServerSocket socketServer = null;
static String settingIp = "localhost";
static String settingPort = "22222";
static byte settingPlayers = 5;
public static int connectedPlayers = 0;
public static void main(String[] args) {
try {
GameMultiPlayerCreate objGameMultiPlayerCreate = new GameMultiPlayerCreate();
objGameMultiPlayerCreate.createServer();
} catch (NumberFormatException | IOException | InterruptedException e) {
e.printStackTrace();
}
}
public void createServer() throws NumberFormatException, UnknownHostException, IOException, InterruptedException {
while (connectedPlayers < settingPlayers) {
socketServer = new ServerSocket(Integer.parseInt(settingPort), 8, InetAddress.getByName(settingIp));
System.out.println("Server is waiting for connection...");
Socket socket = socketServer.accept();
new Thread(new Server(socket)).start();
Thread.sleep(5000);
socketServer.close();
}
}
}
Server.java: This is the Class of which a new Thread should be created for each connected Client (Client Handler)
public class Server implements Runnable {
protected static Socket socket = null;
private int loops;
private int maxLoops = 10;
private int timeout = 10000;
protected static boolean killThread = false;
private boolean authenticated = true; //true for testing
protected static String ip;
protected static int port;
public Server(Socket socket) throws IOException {
Server.socket = socket;
}
public void run() {
try {
socket.setSoTimeout(timeout);
} catch (SocketException e) {
System.out.println("Error while trying to set Socket timeout. ");
System.out.println("Closing Thread..." + Thread.currentThread());
disconnectClient();
}
if (!killThread) {
GameMultiPlayerCreate.connectedPlayers = GameMultiPlayerCreate.connectedPlayers + 1;
loopWaitForData();
}
}
private void disconnectClient() {
System.out.println("Kicking Client... " + Thread.currentThread());
killThread = true;
GameMultiPlayerCreate.connectedPlayers = GameMultiPlayerCreate.connectedPlayers - 1;
}
public void loopWaitForData() {
while (!killThread) {
System.out.println(maxLoops + ", " + loops);
if (maxLoops - loops > 0) {
try {
waitForData();
} catch (SocketTimeoutException e) {
System.out.println("Error occurred while waiting for Data. Thread disconnected? Sending reminder. " + Thread.currentThread());
if (!authenticated) {
System.out.println("Kicking Client: Not authenticated");
disconnectClient();
} else {
commandReminder();
}
} catch (ClassNotFoundException | IOException e) {
loops = loops + 1;
System.out.println("Error occurred while waiting for Data. Waiting for more Data. " + Thread.currentThread());
e.printStackTrace();
loopWaitForData();
}
} else if (maxLoops - loops == 0) {
System.out.println("Error occurred while waiting for Data. Maximum trys reached. Disbanding connection. " + Thread.currentThread());
disconnectClient();
loops = loops + 1;
} else {
System.out.println("Closing Thread..." + Thread.currentThread());
disconnectClient();
}
}
}
private void commandReminder() {
System.out.println("Reminder");
try {
String code = new String("0");
ObjectOutputStream outputObject = new ObjectOutputStream(Server.socket.getOutputStream());
outputObject.writeObject(code);
} catch (IOException e) {
System.out.println("Error occurred while trying to authenticate Client: " + e + " in " + Thread.currentThread());
}
}
public void waitForData() throws IOException, ClassNotFoundException {
String code;
System.out.println("Waiting for Data...");
//Next line is where the error occurres
ObjectInputStream inputObject = new ObjectInputStream(socket.getInputStream());
while ((code = (String) inputObject.readObject()) != null) {
System.out.println("Received Data...");
System.out.println("Input received: " + code);
return;
}
}
}
Client.java: This is the Client
public class Client {
public static Socket socket = new Socket();
private int loops = 0;
private int maxLoops = 10;
private static boolean killThread = false;
private String ip;
private int port;
public Client(String receivedIp, String receivedPort) {
ip = receivedIp;
port = Integer.parseInt(receivedPort);
try {
System.out.println("Trying to connect to Server...");
socket.connect(new InetSocketAddress(ip, port));
System.out.println("Connected!");
} catch (IOException e) {
System.out.println("Error occurred while trying to connect to Server.");
}
loopWaitForData();
}
public static void main(String[] args) {
#SuppressWarnings("unused")
Client objClient = new Client("localhost", "22222");
}
public void loopWaitForData() {
while (!killThread) {
System.out.println(maxLoops + ", " + loops);
if (maxLoops - loops > 0) {
try {
waitForData();
} catch (IOException | ClassNotFoundException e) {
loops = loops + 1;
try {
Thread.sleep(2000);
} catch (InterruptedException e1) {
}
System.out.println("Error occurred while waiting for Data. Waiting for more Data. " + Thread.currentThread());
e.printStackTrace();
loopWaitForData();
}
} else if (maxLoops - loops == 0){
System.out.println("Error occurred while waiting for Data. Maximum trys reached. Disbanding connection. " + Thread.currentThread());
try {
socket.close();
} catch (IOException e) {
System.out.println("Failed to close Socket " + Thread.currentThread());
}
loops = loops + 1;
} else {
System.out.println("Closing Thread..." + Thread.currentThread());
killThread = true;
}
}
}
public void waitForData() throws IOException, ClassNotFoundException {
InputStream input = socket.getInputStream();
ObjectInputStream inputObject = new ObjectInputStream(input);
String code;
System.out.println("Waiting for Data...");
while ((code = (String) inputObject.readObject()) != null) {
System.out.println("Received Data...");
System.out.println("Input received: " + code);
answer();
return;
}
}
private void answer() {
try {
String code = new String("1");
ObjectOutputStream outputObject = new ObjectOutputStream(socket.getOutputStream());
outputObject.writeObject(code);
} catch (IOException e) {
System.out.println("Error occurred while trying to answer: " + e + " in " + Thread.currentThread());
}
}
}
This is my first post, so correct me if I am doing something wrong.
I am trying to make a multithreaded client/server application. I have no problem making a basic 1 to 1 client/server application without threading, but I want every client to talk individually to the server and each client only to recieve the messages that belongs to the particular client in the console. This is where I can't make it work.
I have looked at some tutorials online and I tried to debug in Eclipse without any luck.
What I want the application to do:
If I run the server and 2 clients I want to be able to write a message on a client and make the server return the message and the message number without skipping a number.
Client 1 :
Message no: 0. You said: Hello!
Message no: 1. You said: Whats up!
Client 2 :
Message no: 0. You said: Hey Server!
Message no: 1. You said: What are you doing now?
It works with the first Client that I run and perfectly increment the messagenumber, but when I create the second one it freezes, so I guess my problem is either with the socket declaration or with the way I am threading. (Maybe a socket.close() is missing somewhere?)
I know there is some other flaws with the application, but keep in mind that it is just a school assignment for working with threads.
Thanks in advance if someone is willing to help. :)
Server Code:
public class Server extends Thread
{
DataInputStream in;
DataOutputStream out;
ServerSocket listener;
public Server() throws IOException
{
try
{
while (true)
{
listener = new ServerSocket(9090);
Socket socket = listener.accept();
System.out.println("Test");
ThreadServer ts = new ThreadServer(socket);
Thread t1 = new Thread(ts);
t1.start();
}
}
finally
{
listener.close();
}
}
public static void main(String[] args) throws IOException
{
new Server();
}
}
Client code:
public class Client extends JFrame
{
DataOutputStream dos;
BufferedReader input;
String answer = null;
String textString;
Socket s = new Socket("localhost", 9090);
public Client() throws IOException
{
JButton btn = new JButton("run");
final JTextField txf = new JTextField(10);
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try
{
dos = new DataOutputStream(s.getOutputStream());
textString = txf.getText();
dos.writeUTF(textString);
dos.flush();
input = new BufferedReader(new InputStreamReader(s.getInputStream()));
answer = input.readLine();
}
catch (Exception e1)
{
e1.printStackTrace();
}
System.out.println(answer);
}
});
setLayout(new GridLayout(2,2));
add(btn);
add(txf);
setVisible(true);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) throws IOException
{
new Client();
}
}
ThreadServer code:
public class ThreadServer implements Runnable
{
DataInputStream in;
DataOutputStream out;
public ThreadServer (Socket socket) throws IOException
{
int i = 0;
try
{
while (true)
{
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
try
{
String message = in.readUTF();
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("Message no: " + i + ". You said: " + message);
out.println("Message no: " + i);
}
catch(Exception e)
{
e.printStackTrace();
}
i++;
}
}
finally
{
socket.close();
}
}
#Override
public void run() {
// TODO Auto-generated method stub
}
}
Let me try to solve it.
Create only one ServerSocket. Move below line from while loop. Put it before while loop.
listener = new ServerSocket(9090);
Move the code of ThreadServer's constructor to run() method because it implements Runnable but doesn't behave like a Runnable class.
public ThreadServer(Socket socket) throws IOException {
this.socket=socket;
}
#Override
public void run() {
...
//code from constructor
}
In Server class you are writing two lines to Client but client is reading just one. Remove extra line as shown below
out.println("Message no: " + i + ". You said: " + message);
//out.println("Message no: " + i);
One last suggestion:
Always check for inputs before calling readUTF() as shown below:
if (in.available() > 0) {
try {
String message = in.readUTF();
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("Message no: " + i + ". You said: " + message);
//out.println("Message no: " + i);
} catch (Exception e) {
e.printStackTrace();
}
i++;
}
Your ThreadServer is looping infinitely in the constructor, instead of the run method.
This is very bad. The run method is where you should put that code.
You should also follow the advice in the comment and move the socket creation.
-edit-
same is true for your ThreadServer, don't do the socket init in the loop. just the reading.
You might also discover later that you need an extra thread for the client. As it is now
it seems each client can only receive messages when the action performed button is clicked,
and that is probably not what you want. This will expose some synchronization problems
that you will have to deal with, but most you gui library might actually help you there.
It was a long time since I dealt with swing.
-edit again-
In addition, read up on exception handling. You should decide where you want
to catch the IO exceptions, rather than randomly nesting try/catch and declaring methods
as throwing them.
I've got a little network game I'm making to learn networking in Java, and I'm in need of a little insight into what my program is having issues with. My server program maxes out the heap and burns 100% of the CPU. I'm sure I've got major newbie gotchas in the code, and I'm wondering if anyone would be so kind as to point them out to me, and perhaps detail why it is such a horrible practice.
Basically, the Server class's job is to wait in socket.accept() to deal with new clients. Each client from there gets its own ConnectionThread (which deals with input) and an attached OutputStream (which handles output). I know this may be wasteful for large applications, but with the server running along with just three clients (which are set to skip rendering and only send data through the socket every ~20ms for both input and output) it cooks the CPU and the server overflows the stack.
I've got a Packet class which converts the data into a string for sending, and the receiver decodes it back into a Packet. I suspect I have some Packets laying around too long, but I don't see where. If it isn't the packets, I'm fairly certain I have SOME sort of uncontrolled exponential object growth.
Here are some snippets of relevant code. I'm happy to provide more if the problem is elsewhere.
Just for reference, here is the full code: https://github.com/taylorrobert/ProjectM2O
Server:
public Server() {
network = new NetworkManager(this);
network.setConnectionCounter(0);
entityManager = new EntityManager(this);
setListenState(true);
try {
serverSocket = new ServerSocket(PORT);
} catch (IOException e) {
System.out.println("Error in server constructor.");
System.exit(1);
}
}
public void listen() {
System.out.println("Current connectionCounter: " + network.getConnectionCounter());
while (shouldListen) {
ConnectionThread conn = null;
try {
conn = new ConnectionThread(serverSocket, this);
}
catch (Exception e) {
System.out.println("____Error constructing ConnectionThread. Could there be another instance of the server running?");
e.printStackTrace();
System.exit(1);
}
(new Thread(conn)).start();
System.out.println("Connection count: " + network.getConnectionCounter());
}
}
ConnectionThread:
public ConnectionThread(ServerSocket s, Server ser) {
resetTimer();
setActiveState(false);
server = ser;
//This UUID becomes the client's controllable player ID
//and the ID of this ConnectionThread.
connectionID = String.valueOf(UUID.randomUUID());
try {
socket = s.accept();
System.out.println("Socket ID " + connectionID + " established on: " + socket);
} catch (IOException e) {
System.out.println("Error in ConnectionThread. Is there a server already running on this port?");
}
init();
}
public void init() {
try {
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
catch (IOException e) {
System.out.println("Error in intializing I/O streams.");
System.exit(1);
}
//Create the output thread
OutputStream outputHandler = new OutputStream(this);
new Thread(outputHandler).start();
//Get the client up to date on all relevant data
server.getEntityManager().addPlayerEntity(getConnectionID());
server.getNetwork().pushClientInitState(getConnectionID(), this);
server.getNetwork().addConnection(this);
server.getNetwork().notifyClientsAboutNewPlayer(getConnectionID());
int s = server.getNetwork().getConnections().size();
server.getNetwork().sendConsoleMessage("Players online: " + s, this);
}
public void run() {
setActiveState(true);
System.out.println("Running ConnectionThread...");
while (isActive()) {
//System.out.println("Entity size: " + server.getEntityManager().getEntities().size());
String op = readInputStream();
if (op.equals("")) continue;
Packet packet = Packet.populateNewPacketFromString(op);
try {
incomingOpQueue.put(packet);
} catch (InterruptedException e) {
System.out.println("Server failed to add packet to outgoing queue!");
}
//Take all packets off the incoming queue and execute them in order
while (incomingOpQueue.size() > 0) {
Packet p = incomingOpQueue.poll();
PacketExecutor.executePacket(server, p, this);
}
}
}
public String readInputStream() {
String msg = "";
try {
msg = in.readLine();
msg = msg.replace("\n", "");
msg = msg.trim();
} catch (IOException e) {
return "";
}
return msg;
}
OutputStream:
public void output() {
while (parentCT.isActive()) {
UnitTester.updateAllEntityLocationsToAllClients(parentCT, parentCT.server.getEntityManager().getEntities());
while (parentCT.getOutgoingOpQueue().size() > 0) {
String packet = (parentCT.getOutgoingOpQueue().poll().getString());
if (packet.equals("")) continue;
//System.out.println("Sending " + packet + " to " + parentCT.getConnectionID());
parentCT.getOutput().println(packet);
}
}
}
You probably need to make shouldListen volatile. Otherwise, there's every chance that its value will be cached, and setting it to false in some other thread will make no difference. You are setting it to false right, so that the main loop just doesn't make lots and lots of threads until it maxes out the heap and burns up the CPU?