I'm implementing an JavaFX application which is communicating with a mobile phone via wifi (android).
Therefore I have a server thread on the JavaFX running in a background process:
public class NetworkService implements Runnable {
private final ServerSocket serverSocket;
private final ExecutorService pool;
private RoutePlannerJFX application;
private UserData userData;
public NetworkService(ExecutorService pool,
ServerSocket serverSocket,
RoutePlannerJFX app,
UserData data) {
this.serverSocket = serverSocket;
this.pool = pool;
application = app;
userData = data;
}
public void run() {
try {
while ( true ) {
Socket cs = serverSocket.accept();
pool.execute(new Handler(serverSocket, cs, application, userData));
}
} catch (IOException ex) {
System.out.println("--- Interrupt NetworkService-run");
}
finally {
System.out.println("--- Ende NetworkService(pool.shutdown)");
pool.shutdown(); //keine Annahme von neuen Anforderungen
try {
pool.awaitTermination(4L, TimeUnit.SECONDS);
if ( !serverSocket.isClosed() ) {
System.out.println("--- Ende NetworkService:ServerSocket close");
serverSocket.close();
}
} catch ( IOException e ) { }
catch ( InterruptedException ei ) { }
}
}
}
which has a handler:
public class Handler implements Runnable {
private final Socket client;
private final ServerSocket serverSocket;
private RoutePlannerJFX application;
private UserData userData;
Handler(ServerSocket serverSocket,Socket client, RoutePlannerJFX app, UserData data) {
this.client = client;
this.serverSocket = serverSocket;
application = app;
userData = data;
}
public void run() {
StringBuffer sb = new StringBuffer();
PrintWriter out = null;
try {
System.out.println( "running service, " + Thread.currentThread() );
out = new PrintWriter( client.getOutputStream(), true );
BufferedReader bufferedReader =
new BufferedReader(
new InputStreamReader(
client.getInputStream()));
char[] buffer = new char[100];
int anzahlZeichen = bufferedReader.read(buffer, 0, 100);
String nachricht = new String(buffer, 0, anzahlZeichen);
String[] werte = nachricht.split("\\s");
System.out.println(nachricht+"\n");
POI poi = new POI(nachricht);
userData.addItemToPoiList(poi);
application.setScene("INSTRUCT");
} catch (IOException e) {System.out.println("IOException, Handler-run");}
finally {
System.out.println(sb); //Rückgabe Ergebnis an den Client
if ( !client.isClosed() ) {
System.out.println("****** Handler:Client close");
try {
client.close();
} catch ( IOException e ) { }
}
}
}
}
The application has a public method to change the scene (setScene()).
That's the way I wish I could do it, but now I know, that I cannot switch the scene in my backgroundprocess.
Has anyone an idea how to implement this problem? I need to fire an action, when my backgroundprocess receives a message from the the client, but I don't know what's the best way to do that… I already found javafx.concurrent, but which do I have to use and how?
Thank's in advance!
For the client side you can use either a Task or a Service to run in a separate thread & update the GUI as described in the documentation
You can check this post too JavaFX Async Task
Related
This has been the method so far to send and receive on bluetooth using Java with threading. But how do we do this using Kotlin's latest Coroutines? Alot of this old Java cold no longer translates to Kotlin 1.4+ either in terms of how to do threading. I read Kotlin is now using Coroutines instead of threads like before.
public class MainActivity extends AppCompatActivity {
private static final UUID MY_UUID_INSECURE =
UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66")
public void pairDevice(View v) {
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
Object[] devices = pairedDevices.toArray();
BluetoothDevice device = (BluetoothDevice) devices[0]
ConnectThread connect = new ConnectThread(device,MY_UUID_INSECURE);
connect.start();
}
}
private class ConnectThread extends Thread {
private BluetoothSocket mmSocket;
public ConnectThread(BluetoothDevice device, UUID uuid) {
mmDevice = device;
deviceUUID = uuid;
}
public void run(){
BluetoothSocket tmp = null;
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
tmp = mmDevice.createRfcommSocketToServiceRecord(MY_UUID_INSECURE);
} catch (IOException e) {
}
mmSocket = tmp;
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
} catch (IOException e) {
// Close the socket
try {
mmSocket.close();
} catch (IOException e1) {
}
}
//will talk about this in the 3rd video
connected(mmSocket);
}
}
private void connected(BluetoothSocket mmSocket) {
// Start the thread to manage the connection and perform transmissions
mConnectedThread = new ConnectedThread(mmSocket);
mConnectedThread.start();
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = mmSocket.getInputStream();
tmpOut = mmSocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run(){
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
// Read from the InputStream
try {
bytes = mmInStream.read(buffer);
final String incomingMessage = new String(buffer, 0, bytes);
runOnUiThread(new Runnable() {
#Override
public void run() {
view_data.setText(incomingMessage);
}
});
} catch (IOException e) {
Log.e(TAG, "write: Error reading Input Stream. " + e.getMessage() );
break;
}
}
}
public void write(byte[] bytes) {
String text = new String(bytes, Charset.defaultCharset());
Log.d(TAG, "write: Writing to outputstream: " + text);
try {
mmOutStream.write(bytes);
} catch (IOException e) {
}
}
}
public void SendMessage(View v) {
byte[] bytes = send_data.getText().toString().getBytes(Charset.defaultCharset());
mConnectedThread.write(bytes);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
send_data =(EditText) findViewById(R.id.editText);
view_data = (TextView) findViewById(R.id.textView);
if (bluetoothAdapter != null && !bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
public void Start_Server(View view) {
AcceptThread accept = new AcceptThread();
accept.start();
}
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
public AcceptThread(){
BluetoothServerSocket tmp = null ;
try{
tmp = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord("appname", MY_UUID_INSECURE);
}catch (IOException e){
}
mmServerSocket = tmp;
}
public void run(){
Log.d(TAG, "run: AcceptThread Running.");
BluetoothSocket socket = null;
try{
// This is a blocking call and will only return on a
// successful connection or an exception
socket = mmServerSocket.accept();
}catch (IOException e){
}
//talk about this is in the 3rd
if(socket != null){
connected(socket);
}
}
}
I have been working on a device which is sending some data to an Azure IoT hub
The device is doing this on two different locations in the code. On one side it works perfectly and I can connect to the Hub via Connection String and transport type MQTT_WebSocket_Only.
public static class Mqtt2IoTNew
{
private static string _DeviceConnectionString = Properties.Settings.Default.MqttUri;
private static TransportType _TransportType = TransportType.Mqtt_WebSocket_Only;
public static void Send(object argEntry, bool argIsList)
{
var deviceClient = DeviceClient.CreateFromConnectionString(_DeviceConnectionString, _TransportType);
deviceClient.ReceiveAsync(TimeSpan.FromSeconds(2)).Wait();
var message = new Message(deviceClient, argEntry, argIsList);
message.RunAsync().GetAwaiter().GetResult();
}
}
internal class Message
{
private DeviceClient _DeviceClient;
private readonly string _Message;
public Message(DeviceClient argDeviceClient, object argEntry, bool isList)
{
_DeviceClient = argDeviceClient;
StringBuilder stb = new StringBuilder();
if (isList)
{
foreach (var entity in (List<object>) argEntry)
{
stb.Append("<entity>").Append(JsonConvert.SerializeObject(entity)).Append("</entity>\n");
}
}
else
{
stb.Append(JsonConvert.SerializeObject(argEntry));
}
_Message = stb.ToString();
}
public async Task RunAsync()
{
await SendEvent().ConfigureAwait(false);
}
private async Task SendEvent()
{
Microsoft.Azure.Devices.Client.Message eventMessage = new Microsoft.Azure.Devices.Client.Message(Encoding.UTF8.GetBytes(_Message));
await _DeviceClient.SendEventAsync(eventMessage).ConfigureAwait(false);
}
}
//Call of method that does not work
protected override void DoOnCompleted(IRepository argRepository)
{
if (_CurrentlySendingTreadId.HasValue)
{
if (_CurrentlySendingTreadId.Value == Thread.CurrentThread.ManagedThreadId)
{
return;
}
}
TaskFactoryProvider.GetFactory().StartNew(()=>SendBatchProtocols());
}
public bool SendBatchProtocols()
{
using (var repository = RepositoryProviderHolder.RepositoryProvider.GetRepository(Constants.CONTAINERCONTRACT_PRODUCTIONREPOSITORY))
{
IQueryable<BatchProtocol> batchProtocolQuery = repository.GetQuery<BatchProtocol>().OrderBy(bp => bp.InternalNoInteger);
batchProtocolQuery = batchProtocolQuery.Where(bp => !bp.IsArchived).Take(1);
if (!batchProtocolQuery.Any()) return false;
var batchProtocols = batchProtocolQuery.ToList();
IsBatchProtocolSend = false;
try
{
foreach (var bps in batchProtocols)
{
Mqtt2IoTNew.Send(bps,false);
}
IsBatchProtocolSend = true;
}
catch (Exception ex)
{
throw;
}
}
return IsBatchProtocolSend;
}
//Call of Method that does work
private void AddEntitiesAndSaveChanges(IEnumerable argEntities)
{
if (argEntities == null)
{
return;
}
lock (_UnderlyingRepositoryAccessLockObject)
{
#region Log2DornerIoT
if (Properties.Settings.Default.Log2DornerIoT)
{
List<object> entities = new List<object>();
int i = 0;
foreach (var entity in argEntities)
{
if (i < 100)
{
entities.Add(entity);
i++;
}
else
{
try
{
Mqtt2IoTNew.Send(entities, true);
}
catch (Exception e)
{
throw;
}
entities.Clear();
i = 0;
}
}
}
}
on the other part of the code, I am only colling the same class to use to send method in the same way but here I get an exception which says "TLS authentication error" and the inner exception "Unable to connect to the remote server", "The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel".
But: I never used any kind of authorization not in the first part which works perfectly neither in the second.
I would be very happy if someone could help me. I have found nothing so fare regarding this issue.
Thanks for your time.
Michael
I found the reason why it didn't work. There was a Persmissice Certificate Policy applied that blocked the certificate at one side of the project. I disabled it and now it works perfectly fine.
Thanks for the help anyway.
I need help with creating a windows service using Threading and asynchronous HttpWebRequest calls. I have created a few C# windows services before but never using threading. Also, I seem to be getting hung up with the async calls using HttpWebRequest. I have googled this as well as looking on this site. I could not find anything that helped. This is mainly because I could not seem to get what was presented in other questions to work in my specific example.
Please keep in mind that I may be overlapping things based on my lack of knowledge in this specific area as well as through trying to figure it out.
The main flow of this is to get a list of urls during onStart. Typically this list would be retrieved from a _facade.GetUrls call. Then, at each time interval call scanSites. A request is made to each url and then I save the results to the database in _facade.SaveUrlResponse.
My problems is it seems as if I am caught in an endless loop when I debug it. I am not exactly sure how/where to do this. Thanks in advance.
Here is what I have:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.ServiceProcess;
using System.Threading;
using URLValidation.BusinessManager.Facade;
using URLValidation.BusinessManager.Model;
namespace URLValidation
{
partial class URLValidation : ServiceBase
{
#region " class variables "
private System.Timers.Timer _timer;
private List<UrlModel> _url_List = null;
private Facade _facade;
private Thread _t;
private int _x;
#endregion
public URLValidation()
{
_facade = new Facade();
InitializeComponent();
}
protected override void OnStart(string[] args)
{
try
{
_url_List = new List<UrlModel>
{
new UrlModel(address: "http://www.google.com", addressID: 1),
new UrlModel(address: "http://www.microsoft.com", addressID: 2),
new UrlModel(address: "http://www.stackoverflow.com", addressID: 3)
};
resetTimer();
GC.KeepAlive(_timer);
}
catch (Exception ex)
{
throw ex;
}
}
private void resetTimer()
{
try
{
_timer = new System.Timers.Timer();
_timer.Interval = 10000;//1800000; //30 minutes
_timer.Start();
_timer.Enabled = true;
_timer.Elapsed += scanSites;
}
catch (Exception ex)
{
throw ex;
}
}
private void scanSites(object sender, System.Timers.ElapsedEventArgs e)
{
_timer.Stop();
_x = 0;
_t = new Thread(new ThreadStart(scanSites));
_t.IsBackground = true;
_t.Start();
}
private void scanSites()
{
try
{
foreach (UrlModel url in _url_List)
{
_x += 1;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.Address);
request.Method = "HEAD";
RequestModel requestModel = new RequestModel(request, url);
IAsyncResult result = request.BeginGetResponse(new AsyncCallback(saveUrlResponse), requestModel);
ThreadPool.RegisterWaitForSingleObject
(
result.AsyncWaitHandle,
new WaitOrTimerCallback(ScanTimeoutCallback),
requestModel,
(30 * 1000), // 30 second timeout
true
);
}
}
catch (Exception ex)
{
throw ex;
}
}
private void saveUrlResponse(IAsyncResult result)
{
//grab the custom state object
RequestModel requestModel = (RequestModel)result.AsyncState;
HttpWebRequest request = (HttpWebRequest)requestModel.Request;
//get the Response
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
// process the response...
ResponseModel responseModel = new ResponseModel(request, response, requestModel.UrlModel.AddressID);
_facade.SaveUrlResponse(responseModel);
}
private void ScanTimeoutCallback(object requestModel, bool timedOut)
{
if (timedOut)
{
RequestModel reqState = (RequestModel)requestModel;
if (reqState != null)
reqState.Request.Abort();
}
if (_x == _url_List.Count)
{
resetTimer();
}
}
protected override void OnStop()
{
// TODO: Add code here to perform any tear-down necessary to stop your service.
}
}
}
Okay, I think I am getting somewhere. I have moved my code to a console app. I am able to get the results saved to the database by using either GetResponse (sync) and BeginGetResponse (async). From what I can tell I believe this is a good solution. Can somebody verify this and let me know if you foresee any problems once this is moved to a Windows Service. Here is the new code
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading;
namespace ConsoleApplication2
{
static class Program
{
private static List<UrlModel> _url_List = null;
private static Object _acctLock = new object();
private static Facade _facade = new Facade();
static void Main(string[] args)
{
_url_List = new List<UrlModel>
{
new UrlModel(address: "http://www.microsoft.com", addressID: 1),
new UrlModel(address: "http://www.google.com", addressID: 2),
new UrlModel(address: "http://www.stackoverflow.com", addressID: 3)
};
lockThreadAndGetUrlStatus(_url_List);
Console.ReadLine();
}
static void lockThreadAndGetUrlStatus(List<UrlModel> _url_List)
{
Thread[] threads;
try
{
threads = new Thread[_url_List.Count];
Thread.CurrentThread.Name = "main";
int i = 0;
foreach (UrlModel url in _url_List)
{
//Thread t = new Thread(() => scanSites(url));
Thread t = new Thread(() => scanSitesWithAsync(url));
t.Name = i.ToString();
threads[i] = t;
i += 1;
}
for (i = 0; i < _url_List.Count; i++)
{
Console.WriteLine("Thread {0} Alive : {1}", threads[i].Name, threads[i].IsAlive);
threads[i].Start();
Console.WriteLine("Thread {0} Alive : {1}", threads[i].Name, threads[i].IsAlive);
}
Console.WriteLine("Current Priority : {0}", Thread.CurrentThread.Priority);
Console.WriteLine("Thread {0} Ending", Thread.CurrentThread.Name);
}
catch (Exception ex)
{
throw ex;
}
}
static void scanSitesWithAsync(UrlModel url)
{
try
{
lock (_acctLock)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.Address);
request.Method = "HEAD";
RequestModel requestModel = new RequestModel(request, url);
IAsyncResult result = request.BeginGetResponse(new AsyncCallback(saveUrlResponseWithAsync), requestModel);
ThreadPool.RegisterWaitForSingleObject
(
result.AsyncWaitHandle,
new WaitOrTimerCallback(scanTimeoutCallback),
requestModel, 30000, true
);
}
}
catch (Exception ex)
{
throw ex;
}
}
static void saveUrlResponseWithAsync(IAsyncResult result)
{
try
{
RequestModel requestModel = (RequestModel)result.AsyncState;
HttpWebRequest request = (HttpWebRequest)requestModel.Request;
//get the Response
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
// process the response...
ResponseModel responseModel = new ResponseModel(requestModel.Request, response, requestModel.UrlModel.AddressID);
_facade.SaveUrlResponse(responseModel);
Console.WriteLine(response.StatusCode);
}
catch (Exception ex)
{
throw ex;
}
}
static void scanTimeoutCallback(object requestModel, bool timedOut)
{
try
{
if (timedOut)
{
RequestModel reqState = (RequestModel)requestModel;
if (reqState != null)
reqState.Request.Abort();
}
}
catch (Exception ex)
{
throw ex;
}
}
}
}
looks like you are trying to issue 3 async requests at the same time. By default, the HTTP/1.1 protocol only specifies 2 connections
im writing a multithread chat program where i hope to have a server connected to multiple clients, the clients can talk to each and send messages to each other. I want all messages from the clients to be visible to the server, moreover that the server can send messages to all visible clients. My program only connects the server to one client and they can send messages.
package chatserver2;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
// import all the class that you will need for functionailty
// extends jframe to develop gui's in java
public class Server2 {
private static JTextField userInput; //
private static JTextArea theChatWindow; //
private static ObjectOutputStream output; // stream data out
private static ObjectInputStream input; // stream data in
private static ServerSocket server;
private static Socket connection; // socket means set up connetion between 2 computers
private static JFrame frame;
private static int n;
//Constructor
public static void main(String[] args) throws IOException {
Server2 obj = new Server2();
// Socket sock=new Socket("localhost",6789);
System.out.println("Hello 4");
obj.RunServer();
System.out.println("Hello 3");
try {
while (true) {
System.out.println("Hello 2");
Handler obj2 = new Handler();
//Handler obj3=new Handler();
obj2.start();
System.out.println("Accepted connection from "
+ connection.getInetAddress() + " at port "
+ connection.getPort());
n++;
System.out.println("Count " + n);
}
} finally {
connection.close();
}
}
public Server2() {
frame = new JFrame();
userInput = new JTextField();
userInput.setEditable(false); // set this false so you dont send messages when noone is available to chat
// action event listener to check when the user hits enter for example
userInput.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
sendMessage(event.getActionCommand()); // string entered in the textfield
userInput.setText(""); // reset text area to blank again
}
}
);
// create the chat window
frame.add(userInput, BorderLayout.NORTH);
theChatWindow = new JTextArea();
frame.add(new JScrollPane(theChatWindow));
frame.setSize(300, 150);
frame.setVisible(true);
}
// run the server after gui created
public void RunServer() {
try {
server = new ServerSocket(6789); // 1st number is port number where the application is located on the server, 2nd number is the amount of people aloud to connect
while (true) {
try {
waitForConnection(); // wait for a connection between 2 computers
setupStreams(); // set up a stream connection between 2 computers to communicate
whileChatting(); // send message to each other
// connect with someone and have a conversation
} catch (EOFException eofException) {
showMessage("\n Server ended Connection");
}
}
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
//Wait for a connection then display connection information
private void waitForConnection() {
showMessage("waiting for someone to connect to chat room....\n");
try {
connection = server.accept();
} catch (IOException ioexception) {
ioexception.printStackTrace();
}
showMessage("Now connected to" + connection.getInetAddress().getHostName());
showMessage(" at port " + connection.getPort());
}
// stream function to send and recive data
private void setupStreams() throws IOException {
output = new ObjectOutputStream(connection.getOutputStream()); // set up pathway to send data out
output.flush(); // move data away from your machine
input = new ObjectInputStream(connection.getInputStream()); // set up pathway to allow data in
// String message = "WAIT";
// sendMessage(message);
//showMessage("\n Connection streams are now setup \n");
}
// this code while run during chat conversions
private void whileChatting() throws IOException {
String message = "WAIT ";
sendMessage(message);
allowTyping(true); // allow user to type when connection
do {
// have conversion while the client does not type end
try {
message = (String) input.readObject(); // stores input object message in a string variable
showMessage("\n " + message);
System.out.println("Message from Client " + message);
} catch (ClassNotFoundException classnotfoundException) {
showMessage("\n i dont not what the user has sent");
}
} while (!message.equals("CLIENT - END"));// if user types end program stops
}
private void closeChat() {
showMessage("\n closing connections...\n");
allowTyping(true);
try {
output.close(); // close output stream
input.close(); // close input stream
connection.close(); // close the main socket connection
} catch (IOException ioexception) {
ioexception.printStackTrace();
}
}
// send message to the client
private void sendMessage(String message) {
try {
output.writeObject(message);
output.flush(); // send all data out
showMessage("\nServer - " + message);
System.out.println("Message to client " + message);
} catch (IOException ioexception) {
theChatWindow.append("\n ERROR: Message cant send");
}
}
// update the chat window (GUI)
private void showMessage(final String text) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
theChatWindow.append(text);
}
}
);
}
// let the user type messages in their chat window
private void allowTyping(final boolean trueOrFalse) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
userInput.setEditable(trueOrFalse);
}
}
);
}
public static class Handler extends Thread {
private Socket connection;
// static private ServerSocket server;
public Handler() {
// this.socket = socket;
String message = "WAIT";
}
//connection = server.accept();
public void run() {
System.out.println("Connect" + Server2.connection);
while (true) {
try {
waitForConnection();
setupStreams();
whileChatting();
} catch (IOException ex) {
Logger.getLogger(Server2.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private void waitForConnection() {
System.out.println("Heelo");
showMessage("waiting for someone to connect to chat room....\n");
System.out.println("server" + server);
try {
connection = server.accept();
} catch (IOException ioexception) {
ioexception.printStackTrace();
}
System.out.println("Connection" + connection);
showMessage("Now connected to" + connection.getInetAddress().getHostName());
showMessage("AT port" + connection.getPort());
}
private void setupStreams() throws IOException {
output = new ObjectOutputStream(connection.getOutputStream()); // set up pathway to send data out
output.flush(); // move data away from your machine
input = new ObjectInputStream(connection.getInputStream()); // set up pathway to allow data in
showMessage("\n Connection streams are now setup \n");
}
// this code while run during chat conversions
private void whileChatting() throws IOException {
String message = " You are now connected ";
sendMessage(message);
allowTyping(true); // allow user to type when connection
do {
// have conversion while the client does not type end
try {
message = (String) input.readObject(); // stores input object message in a string variable
showMessage("\n " + message);
} catch (ClassNotFoundException classnotfoundException) {
showMessage("\n i dont not what the user has sent");
}
} while (!message.equals("CLIENT - END"));// if user types end program stops
}
private void closeChat() {
showMessage("\n closing connections...\n");
allowTyping(true);
try {
output.close(); // close output stream
input.close(); // close input stream
connection.close(); // close the main socket connection
} catch (IOException ioexception) {
ioexception.printStackTrace();
}
}
// send message to the client
static private void sendMessage(String message) {
try {
output.writeObject(message);
output.flush(); // send all data out
showMessage("\nServer - " + message);
} catch (IOException ioexception) {
theChatWindow.append("\n ERROR: Message cant send");
}
}
// update the chat window (GUI)
static private void showMessage(final String text) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
theChatWindow.append(text);
}
}
);
}
// let the user type messages in their chat window
private void allowTyping(final boolean trueOrFalse) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
userInput.setEditable(trueOrFalse);
}
}
);
}
}
}
Here is the client :
package chatserver2;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
// import all the class that you will need for functionailty
// extends jframe to develop gui's in java
public class Client2 extends JFrame {
private JTextField userInput; //
private JTextArea theChatWindow; //
private ObjectOutputStream output; // stream data out
private ObjectInputStream input; // stream data in
private Socket connection; // socket means set up connetion between 2 computers
//Constructor
public Client2() {
super("My Chat Service");
userInput = new JTextField();
userInput.setEditable(false); // set this false so you dont send messages when noone is available to chat
// action event listener to check when the user hits enter for example
userInput.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
sendMessage(event.getActionCommand()); // string entered in the textfield
userInput.setText(""); // reset text area to blank again
}
}
);
// create the chat window
add(userInput, BorderLayout.NORTH);
theChatWindow = new JTextArea();
add(new JScrollPane(theChatWindow));
setSize(300, 150);
setVisible(true);
}
// run the server after gui created
public void RunServer() {
try {
connection = new Socket("localhost", 6789);// 1st number is port number where the application is located on the server, 2nd number is the amount of people aloud to connect
while (true) {
try {
// wait for a connection between 2 computers
setupStreams(); // set up a stream connection between 2 computers to communicate
whileChatting(); // send message to each other
// connect with someone and have a conversation
} catch (EOFException eofException) {
showMessage("\n Server ended Connection");
} finally {
closeChat();
}
}
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
//Wait for a connection then display connection information
// stream function to send and recive data
private void setupStreams() throws IOException {
output = new ObjectOutputStream(connection.getOutputStream()); // set up pathway to send data out
output.flush(); // move data away from your machine
input = new ObjectInputStream(connection.getInputStream()); // set up pathway to allow data in
showMessage("\n Connection streams are now setup \n");
}
// this code while run during chat conversions
private void whileChatting() throws IOException {
String message = "";
allowTyping(true); // allow user to type when connection
do {
// have conversion while the client does not type end
try {
message = (String) input.readObject(); // stores input object message in a string variable
System.out.println("message " + message);
if (message.equals("WAIT")) {
ServerSocket server2 = new ServerSocket(5000);
System.out.println("Hello");
message = "5000";
sendMessage(message);
}
System.out.println("From server " + message);
showMessage("\n " + message);
} catch (ClassNotFoundException classnotfoundException) {
showMessage("\n i dont not what the user has sent");
}
} while (!message.equals("CLIENT - END"));// if user types end program stops
}
private void closeChat() {
showMessage("\n closing connections...\n");
allowTyping(true);
try {
output.close(); // close output stream
input.close(); // close input stream
connection.close(); // close the main socket connection
} catch (IOException ioexception) {
ioexception.printStackTrace();
}
}
// send message to the client
private void sendMessage(String message) {
try {
output.writeObject(" - " + message);
output.flush(); // send all data out
showMessage("\nServer - " + message);
} catch (IOException ioexception) {
theChatWindow.append("\n ERROR: Message cant send");
}
}
// update the chat window (GUI)
private void showMessage(final String text) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
theChatWindow.append(text);
}
}
);
}
// let the user type messages in their chat window
private void allowTyping(final boolean trueOrFalse) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
userInput.setEditable(trueOrFalse);
}
}
);
}
public static void main(String[] args) {
Client2 obj = new Client2();
obj.RunServer();
}
}
I am having trouble coding the socket side of a JavaFX chat client. This is my first time having to deal with socket in any sort of way, so some trouble was expected. I've been following this page to design the server-client side:
http://pirate.shu.edu/~wachsmut/Teaching/CSAS2214/Virtual/Lectures/chat-client-server.html
My problem is getting text I enter into the GUI into a DataInputSteam and DataOutputStream so that others on the same server can see the changes. I do
not understand how to convert the text in the UI to something the sockets
can work with.
Here is part of my controller class:
#FXML
private TextArea messageArea;
#FXML
private Button sendButton;
private ChatClient client;
#FXML
public void initialize() {
client = new ChatClient(ChatServer.HOSTNAME, ChatServer.PORT);
sendButton.setOnAction(event -> {
client.handle(messageArea.getText());
});
}
The ChatClient class is a Runnable with a DataInputStream and DataOutputStream field that connects to a Socket. I haven't changed much from the link:
public class ChatClient implements Runnable {
private Socket socket;
private Thread thread;
private DataInputStream streamIn;
private DataOutputStream streamOut;
private ChatClientThread client;
public ChatClient(String serverName, int port) {
System.out.println("Establishing connection...");
try {
socket = new Socket(serverName, port);
System.out.println("Connected: " + socket);
start();
} catch (UnknownHostException e) {
System.out.println("Unknown host: " + e.getMessage());
} catch (IOException e) {
System.out.println("Unexpected: " + e.getMessage());
}
}
#Override
public void run() {
while (thread != null) {
try {
streamOut.writeUTF(streamIn.readUTF());
streamOut.flush();
} catch (IOException e) {
System.out.println("Sending error: " + e.getMessage());
stop();
}
}
}
public void handle(String msg) {
try {
streamOut.writeUTF(msg);
streamOut.flush();
} catch (IOException e) {
System.out.println("Could not handle message: " + e.getMessage());
}
System.out.println(msg);
}
public void start() throws IOException {
streamIn = new DataInputStream(socket.getInputStream());
streamOut = new DataOutputStream(socket.getOutputStream());
if (thread == null) {
client = new ChatClientThread(this, socket);
thread = new Thread(this);
thread.start();
}
}
So in the controller class, I am calling the handle method which deals with the streams. The original code just wrote to the console, so I had to change the line:
streamIn = new DataInputStream(System.in)
to
streamIn = new DataInputStream(socket.getInputStream());
There is also a ChatClientThread class that extends Thread and just calls ChatClient.handle() in its run method.
I guess my question is how to update a GUI whenever writeUTF and readUTF interact with the DataStreams. I understand that streamOut.writeUTF(msg) changes the DataOutputStream to "have" that string, but I'm not sure how I'm supposed to use that datastream to update my gui so that all clients using the application can see the update. The way I have it now, if I run two instances of the JavaFX app, they dont' communicate through the UI or the console. My program just stalls whenever I click the send button