Java UDP Sockets And Multi-Threading
Dec 26, 2014
I have been practicing writing java code, my university course is going to cover socket programming and multi-threading.
I am presently just starting to write myself a framework for all multiplayer games I may make in the future, my aim really is simply to practice and understand better and this time, im not using an ide, just sublime text, all new grounds for me, I have a good basic understanding of the subject but I want to be fluent.
import java.net.*;
import java.util.ArrayList;
import java.io.*;
/*SMOOTH THREAD SAFE MULTI CLIENT HANDLING CLASS.
*
*This class will create connection objects when a connection is detected, these connections will run in a separate thread and update an array list in their parent class containing their last sent data
[Code] .....
View Replies
ADVERTISEMENT
Feb 6, 2015
Firstly, my code is just a demo of my multiplayer game (2 or more players can play simultaneously) to demonstrate my problem without any extra things. I have successfully implemented peer-to-peer (P2P) communication in my game. Later, I decided to add support for client-server communication (ie a central server which is also a player) in my game. It should be much easier than P2P. Now here is the problem:
Suppose, I have 1 server and some clients (may be 1 or more clients). They all should give the following output:
Starting...
A
B
C
E
F
...
...
Done!
They all give the above output without using multi-thread. But using multi-threading, it gives the above output only when there're 1 server and 1 client. I'm using 2 threads (1 for sending, 1 for receiving) for each Socket. That means, each client has only 2 threads for communication but the server has (2 * totalClients) threads.
I've attached my full test project. So, here I'm only showing my 2 thread classes.
ReceiveThread class:
class ReceiveThread extends Thread {
private ObjectInputStream receiveStream;
private BlockingQueue<Character> queue = new ArrayBlockingQueue<Character>(Common.totalClients);
[Code] ....
Since I've attached my full test project, I'm not showing the other 3 classes. They are ServerMain, ClientMain and Common. If I've 2 clients to be connected, then I get the following output:
Server: (Runs first)
Starting...
A
Client 1 (clientID is 1): (Runs after the server)
Starting...
A
B
B
Client 2 (clientID is 2): (Runs after Client 1)
Starting...
A
They are stuck at there, even no exception. Actually, the server and the clients are stuck at the line try { ch = queue.take(); } if more than 1 client are connected. It seems that all are trying to receive data. But without using the dedicated threads, they all work as expected even for more than 1 client. Why is this behaviour? How to solve it? Note that I have used the same SendThread and ReceiveThread classes by which I have succcessfully implemented P2P communication.
About my attached test project file:
It has 5 small .java files for the classes as stated above. It is currently faulty when using additional threads. You have to change clientID variable for each client (they are described inside). But it works as expected without additional threads. To test it without the additional threads:
Comment " TODO" linesUncomment the single lines just after " TODO" linesComment the additional thread construction lines (4 lines)
Currently, for a workaround, I'm not using the dedicated threads for sending and receiving data only for client-server communication in my multi-player game. But I'm still using these threads for P2P communication. I don't know why it is and how to solve it.This is the attached test project file as described above.
Attached File(s) : Test Project.zip (4.11K)
View Replies
View Related
Nov 16, 2014
Is there any specific name for servlet's multi threading mechanism? I mean any technical term for it.
View Replies
View Related
Feb 2, 2015
I have a problem with multi threading calling with for loop. I have those two and many other classes in one jar file but n 2 different packages.
When i execute the jar file first runs the Aclass, from where i try to run multi threads. From the run() of the class RunTheGame i call many other classes which are in the same package. Like you can see from the for loop is executed the threads.
The problem is that when the second thread starts the first one is stopped this happens for all the threads, more simply when a new thread starts the old one is dead.
It seems that liken the threads uses the classes called from run() of the class RunTheGame as non multi threaded. It gives this error:
Java Code:
Exception in thread "Thread-0" java.lang.NullPointerException
at thePackage2.EClass.getWhiteRemaining(EClass.java:49)
at thePackage2.EClass.isFinal(DClass.java:84)
at thePackage2.Spiel.<init>(Cclass.java:76)
at thePackage2.RunTheGame.run(RunTheGame.java:198)
at java.lang.Thread.run(Thread.java:745) mh_sh_highlight_all('java');
All the above refereed classes are called from the from run() of the class RunTheGame . Like i understand all the threads use those classes as non thread autonomous classes.
Java Code:
public class Aclass {
private static Thread t[];
public static void main(String[] args) throws IOException {
for (int Game = 0; Game< 10; Game++) {
t[Game] = new Thread(new thePackage2.RunTheGame(aplayer, bplayer, Name, ID , Pmach));
t[Game].start();
[Code] .....
View Replies
View Related
Jul 9, 2014
Just some questions regarding a Consumer producer program I am not understanding. Here are the two classes Below and my questions are :
1. In the main method for NamedConsumer, we created an instance of the class and call it "consumer" and we start it. Then we create another instance and we give its reference to the same variable. Doesn't this in turn destroy the original reference of the first instance we created which was started? Could we have done
NamedConsumer consumer1 = new NamedConsumer( "One", producer );
new Thread( consumer1 ).start();
NamedConsumer consumer2 = new NamedConsumer( "Two", producer );
new Thread( consumer2 ).start();
2. we called start on two difference instances of the NameConsumer class. Doesn't the "run" method need to be synchronized since two threads are hitting it?
Producer.Java
Java Code: public class Producer implements Runnable
{
static final int MAXQUEUE = 5;
private List<String> messages = new ArrayList<String>();
public void run() {
while ( true ) {
putMessage();
try {
Thread.sleep( 1000 );
[code]...
View Replies
View Related
Feb 14, 2014
I have been trying for days and nights , no compile error , but alot of NPEs error .......
This is my Test program
import java.util.*;
public class Test
{
public static void main (String[]args)
{
int totalShares = 0 ;
double totalCost = 0.0;
double totalProfitLoss = 0.0;
[Code] ....
I am expecting a output like this (Which I have error running:
Tracking of Stock : FCS
8 shares has been brought at $37.61
Total shares now 8 at total cost $300.88
33 shares has been brought at $36.31
Total shares now 41 at total cost $1499.11
17 shares has been sold at $42.67
Total shares now 24 at total cost $773.72
19 shares has been sold at $32.31
Total shares now 5 at total cost $159.83
31 shares has been brought at $33.85
Total shares now 36 at total cost $1209.18
28 shares has been brought at $36.37
Total shares now 64 at total cost $2227.54
20 shares has been brought at $35.49
Total shares now 84 at total cost $2937.34
At $36.00 per share, profit is $86.66
View Replies
View Related
Apr 8, 2014
I have written a java code to transfer files from one server to another using the concept of socket programming. I got the codes from another java forum that meet my requirements. The program is said to transfer large sized files (like .mkv , .mprg movies) from one machine to another and can be used to transfer files of all formats. But after running the codes I found that the program is not able to transfer large sized files such as movies and even pdf of sizes 80mb or 111mb. When i transfer small sized files, it gets transferred and the output shows that. You can run the codes and observe it. But when i try to transfer large sized files, the program goes on running for hours. The large sized files are not getting transferred. The program has used bytebuffer but still this error occurs.
**ClientMain.java**
import java.io.IOException;
import java.net.Socket;
public class ClientMain
[code]....
Note that:-
1. ClientMain.java and DirectoryTxr.java are the two classes under client application.
2. ServerMain.java and DirectoryRcr.java are the two classes under Server application.
3. run the ClientMain.java and ServerMain.java simultaneously
Also specify the source directory, destination directory and host address of the machine in which server is running in the ClientMain.java(as per your computer). Here we are not specifying source file ,instead a source directory or folder is specifying.So the entire files of source directory will be transferred.
View Replies
View Related
Apr 3, 2014
I'm working on an assignment right now which involves passing a variable series of numbers to the Server to be sorted into the correct order and returned to the client.
So far I have it connecting to the server and asking for my numbers, and I am entering each number and pressing return, and it is accepting each number individually.
One (smaller I think) problem i'm having is with the client code, specifically the while loop.. I've tried to code it so that when I enter a full stop ('.') the program will stop asking me for more numbers and move on to sending them to the server.. but instead it just crashes giving an error.. heres an example
"Enter a number: 1
Enter a number: 3
Enter a number: 2
Enter a number: 1.
java.lang.NumberFormatException: For input string: "1."
at java.lang.NumberFormatException.forInputString(Num berFormatException.java:65)
[Code] ....
Here's the client code in full
package numberSortprogram;
import java.io.*;
import java.net.ServerSocket;
public class NumSortClient {
public static void main(String[] args) {
InputStreamReader is = new InputStreamReader(System.in);
[Code] ....
The big problem that I have is figuring out how to send the sorted array back to the client..
So, what im trying to get to happen is-
-Client is asked to enter numbers
-Client enters series of numbers into an array
-Array is converted to a string and sent to the server
-String is then split into an array of strings and sorted using compareTo (don't know if this is the best way?)
-Sorted array is sent back to client and displayed.
fyi this is making use of streamsockets..
All of the rest of my code is below:
package numberSortprogram;
import java.io.IOException;
import java.net.*;
import java.util.regex.PatternSyntaxException;
public class NumSortServer {
public static void main(String[] args) {
int serverPort = 4444; // default port
if (args.length == 1 )
[Code] .....
View Replies
View Related
Oct 6, 2014
I have an application written in Java on the Linux platform. My application will work the following way:
User A will open application. User B will open application.User A will need to send User B a message but without a socket connection.User B will need to send User A a message but without a socket connection.The user should be able to identify the messages sent to each other.If User A reads user B's message the message will no longer be available in the channel of communication.If one user exits their application their message should be removed.User C should not be able to read user A and user B message (This is only via the application design, no real security here).Applications should be able to work on different machines however they will utilize a shared network mount to access files modified by each other.
I do have to note that the messages being sent is rather small and only 1 message is sent from each user, so in that regard I did not want to setup a client/server model to do this using sockets.
Basically I am looking for a similar concept as a message queue but more relevant to my requirements done in Java. What are some good options to use that will address some of my requirements? I have not touched Java in a long time and only have used it for certain usage so I am trying to get an idea of which current technologies are best for what I need.
View Replies
View Related
May 31, 2014
I am trying to make a Connect Four game with java swing, but I am getting an error with my attempt at making an multi D panel maker when I try to run it.
import javax.swing.*;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
[code]...
View Replies
View Related
Nov 20, 2014
I have an application that uses multiple threads to access logic. I am using joda time to compare dates because joda time is thread safe. Below is the example method I am using. My question is being that joda time is thread safe, does it matter whether or not I am using a static method rather than an instance method?
Java Code:
public static boolean isDateEqual(Date checkedDate, String targetDateString) {
boolean passed = false;
if (checkedDate != null && targetDateString != null && !targetDateString.equals("")) {
DateTime checkedDateTime = new DateTime(checkedDate);
DateTimeFormatter fmt = DateTimeFormat.forPattern("MM/dd/yyyy");
DateTime targetDateTime = fmt.parseDateTime(targetDateString);
if (DateTimeComparator.getDateOnlyInstance().compare(checkedDateTime, targetDateTime) == 0) {
passed = true;
}
}
return passed;
} mh_sh_highlight_all('java');
View Replies
View Related
Jun 22, 2014
HOW does threading prevent GUI unresponsiveness?
View Replies
View Related
Dec 26, 2014
I have just started learning about sockets and such... and i have created a chat program with a server and a client
server:
public class Server {
private static ServerSocket server;
private static Socket connection;
private static PrintWriter pw;
private static BufferedReader br;
private static JTextField textOutput;
[Code] ....
so, everything is working fine . There is only one thing i would like to do now: make it so that i can run the server from my computer and then others can run the client from theirs and we will be able to chat . So I tried:
In the client code on line 56 is says:
connection = new Socket("localhost",7777);
So I changed "localhost",7777 to "myip",7777)
But when i run the server on my computer and run the client on another computer i get this error:
java.net.ConnectException: Connection refused: connect
Why is the connection getting refused? is it for security reasons? so hackers cant connect to me or something? And is there a way to tell your computer to allow that client to connect?
View Replies
View Related
Mar 13, 2014
I am having a problem passing an int value from one class to the other. The gist of the objective of this program is to compute a local sum at each client, and then once the local sums are computed.. to compute the overall sum from all the clients. My problem is that I'm having trouble figuring out how to pass each sum from each individual client in the class multicastSenderReceiver to the readThread class. I keep getting an error.
I feel that I have to be able to pass the sum value from each client generated in multicastSenderReceiver to the other class, because that is the only way I'll accurately be able to sum up all the values..
Java Code:
package multicastsenderreceiver;
import java.net.*;
import java.io.*;
import java.util.*;
//import static multicastsenderreceiver.multicastSenderReceiver.numProcesses;
class multicastSenderReceiver{
[code]....
View Replies
View Related
Dec 6, 2014
I have all of my code written, but it is not producing any output and i'm not sure why.
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
[code]...
View Replies
View Related
Apr 11, 2014
Generally Socket Programming uses HTTP Protocol to send and receive messages in Java. Can we try to exchange HTTP/HTTPS requests instead of TCP?
a Socket constructs a HTTP request to send to another socket from information it has and sends to another one and Server responds with HTTPResponse.
View Replies
View Related
Aug 16, 2012
I created an instant messenger using java. When I have the Server that communicates between the clients and one client running on my Computer the CPU Usage is at 100%. It really slows down everything else I'm doing and I figure this might be an issue if I gave this to people to use. I don't want the client taking up a lot of CPU Usage if they're just running it in the background while doing other things on their computer. The program utilizes multithreading. Each thread is constantly being polled for input.
The Server, as seen below, has two threads. I explain what the threads do before the code. There is also another while loop running constantly in the server that is waiting for sockets to connect. The loop does not run constantly at the line socket.accept(); it stops and just waits.
The User, split into a menu and chat window, has two threads as well. I explain what the threads do before the code. After I originally posted I put a 100 ms sleep in all my threads. CPU Usage is still at 100%*
This thread listens for input from the user. The input tells the server what action to take. There is a thread running for every user currently connected to the server.
public void run()
{
try
{
input = new DataInputStream(user.getSocket().getInputStream());
output = new DataOutputStream(user.getSocket().getOutputStream());
[code]....
View Replies
View Related
May 7, 2014
This question has confused me because "Errors" are capitalized and I'm not sure what they mean.
To me this question is false. Sockets can be used to transfers file over a network.
I can't see why this wouldn't work. The code looks fine to me.
I don't think this is true unless you're using the mouseEntered() or mouseExited() method. But again, I'm not sure.
I think this is true, I don't know what else could have listeners.
They're only worth a few marks each so the answer is only suppose to be a line or two. They are all true or false questions that require an explanation.
View Replies
View Related
May 26, 2014
I am working on a project with client/server relationship and I want the client to be able to transfer their personal music files over the socket. Every time I attempt to do it the file is created but it is empty.
Server code:
Java Code:
public class Server extends JFrame {
//===============================
// FIELDS
//===============================
// connection essentials
private ServerSocket server;
private Socket connection;
[Code] ....
View Replies
View Related
Mar 9, 2014
I have made a server/multi Clients where Clients send Double data but my problem is that the clients send this data to Server only wonce, and the server waits again the connection from client. (I have to run the clients manually each time)what i'm looking: the client should always send data to server. like an infinite loop.
View Replies
View Related
May 18, 2014
Java Code:
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Screen implements ActionListener {
public JButton[][] b=new JButton[200][200];
[Code] ....
I am trying to create the A* Algorithm and I REALLY need a 2D array to handle this.
This is the error:
Java Code:
at java.awt.AWTEventMulticaster.componentShown(AWTEventMulticaster.java:162)
at java.awt.AWTEventMulticaster.componentShown(AWTEventMulticaster.java:162)
at java.awt.AWTEventMulticaster.componentShown(AWTEventMulticaster.java:162)
at java.awt.AWTEventMulticaster.componentShown(AWTEventMulticaster.java:162)
at java.awt.AWTEventMulticaster.componentShown(AWTEventMulticaster.java:162) mh_sh_highlight_all('java');
View Replies
View Related
May 18, 2014
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
[Code]....
I am trying to program an A* algorithm and I cannot even get past the buttons. I need a 2D array of buttons to handle this problem but I am getting the following errors.
at java.awt.AWTEventMulticaster.componentShown(AWTEventMulticaster.java:162)
at java.awt.AWTEventMulticaster.componentShown(AWTEventMulticaster.java:162)
at java.awt.AWTEventMulticaster.componentShown(AWTEventMulticaster.java:162)
at java.awt.AWTEventMulticaster.componentShown(AWTEventMulticaster.java:162)
[Code] ....
View Replies
View Related
May 17, 2015
Whilst pre-preparing for java certification, one of the online mock exams has slightly confused me by saying my answer was incorrect for multi-dimension array 'declaration and instantiation'.
This is one of the answers i chose - which was marked as incorrect
a)
int[][] array2d = {{123}, {4,5}};
Which looks absolutely fine to me.One of the other answers, which i agree is correct and so does the mock exam is
b)
int [][] array2d = new int[2][2];
View Replies
View Related
Nov 22, 2014
My task is to create multiuser console chat program. During whole day of poking around , i finally stand on such concept:
1. When running , Server part must stay into while(true) loop and create threads on each ServerSocket.accept() call, providing socket object inside thread. i.e.
while (true){
System.out.println("Waiting for client to connect");
Thread t = new Thread(new Runner(servSocket.accept(),listOfClientSockets));
System.out.println("Starting thread");
t.start();
}
2. Client side always stays within while(true) loop and waiting for user input with ScannerInstance.nextLine() method.
As soon as user prints something and hits enter, data being captured from scanner and thrown to socket output stream to the server.
My question is : if all parties (X clients and server) are actually in waiting mode (server is waiting for connections and each client is waiting for user input), who will refresh the screen for each client to draw the messages other parties sent?
At this time , each party see updates only when he hits enter and while loop does next iteration reading data from buffer and displaying on console.
View Replies
View Related
Jul 12, 2014
I have written following code.
I want to print all elements in Array to output here is my code
int[][] arr={{12,12,13},
{14,1223,14}};
for(int i=0;i<arr.length;i++)
{
for(int j=0;j<arr.length;j++)
{
System.out.println(arr[i][j]);
}
}
but I am getting following output
12
12
14
1223
how to print all elements of int array?
View Replies
View Related
Apr 10, 2015
I would like to create list of entities which is populated by a search function with the data coming from our REST webservice. However I would like it to be multi-line, with the first line being details from the entity itself and the second line buttons for options that can be performed.
So as an example say my entity is People, the first line would contain columns for first name, last name, gender, DOB, etc. The second line would be buttons for "Edit Person", "Print Person details". With the standard TableView I can't see anyway to alternate between one row of data and another row of buttons.
View Replies
View Related