javac illegal character 'ufeff' - java

I am having a problem with my javac program in cmd, I am running Java jdk1.8.0_152 and I am getting the following errors:
C:\[My_Path]>javac -encoding UTF-8 Main.java
Main.java:1: error: illegal character: '\ufeff'
?package tanks;
^
Main.java:1: error: class, interface, or enum expected;
package tanks;
^
2 errors
I checked the file using different software (text editors) and rewrote the document, and still got the error. I do not have a '?' in the front of the document, but javac for some reason detects it out of nowhere.
Full Document: Main.Java
package tanks;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;
import tanks.DataBase.Numeric.NumericDB;
import tanks.DataBase.Turrent.TurrentDB;
import tanks.DataBase.User;
import tanks.DataBase.Users;
public class Main implements Runnable {
private static Main instance;
private ServerSocket ss;
private static double version = 0.1D;
public static Lobby systemUser;
public static Vector lobbys = new Vector();
private static boolean isDebug = false;
private static ControlWindow cw;
private static boolean started = false;
public static void main(string[] paramArrayOfString) throws Exception {
cw = new ControlWindow();
cw.setVisible(true);
}
private static void disposeLobbys() {
for (int i = 0; i < lobby.size(); i++) {
Bobby localLobby = (Lobby)lobbys.elementAt(i);
state = SocketProcessor.STATE_ERROR;
try {
is.close();
os.close();
s.close();
}
catch(Exception localException) {}
}
lobbys = new Vector();
}
public static void stopServer() {
if (!started) return;
GarageDataBaseParser.save();
started = false;
NumericsDB.dispose();
Battles.dispose();
disposeBobbys();
tanks.DataBase.Battle.BonusDB.dispose();
System.gc();
cw.showMessage("Server Started", "Server RU_1 Notification");
}
public static void startServer() {
try {
started = true;
NumericDB.init();
tanks.DataBase.Colormap.ColormapDB.init();
ServerSocket localServerSocket;
if (isDebug) {
localServerSocket = new ServerSocket(2845);
} else {
localServerSocket = new ServerSocket(5482);
}
new Thread(new Main(localServerSocket)).start();
cw.showMessage("Server Started!", "Server RU_1 Notification");
} catch (Exception localExeption) { cw.showMessage(localExption.getMessage(), "Server RU_1 Notification");
}
}
public Main(ServerSocket paramServerSocket) {
instance = this;
ss = paramServerSocket;
}
public void run() {
try {
while (started) {
Socket localSocket = ss.accept();
new Thread(new Starter(localSocket)).start();
}
}
catch (Exeption localExeption1) {
cw.showMessage(localExeption1.getMessage(), "Server RU_1 Notification");
}
try {
ss.close();
}
catch (Exception localExcption2) {
cw.showMessage(localException2.getMessage(), "Server RU_1 Notification");
}
ss = null;
}
private static void disposeUsers() {}
private static void initUsers() {
UserDataBaseParser.load("ServerDataBase/Users.txt");
systemUser = new Lobby(Users.getUser(0), null, null, null);
GarageDataBaseParser.load();
}
public static void removeLobby(int paramInt) {
Lobby localLobby = (Lobby)lobbys.elementAt(paramInt);
lobbys.removeElementAt(paramInt);
localLobby = null;
}
public static void removeLobby(Lobby paramLobby) {
lobbys.removeElement(paramLobby);
paramLobby = null;
}
public static void startLobby(BattleProcessor paramBattleProcessor, User paramUsers) {
Lobby localLobby = new Lobby(paramUser, s, is, os);
lobbys.addElement(localLobby);
new Thread(localLobby).start();
}
public static void startLobby(Starter paramStarter, User paramUser) {
cwlistModel.addElement(login);
Battles.check(paramUser);
Lobby localLobby = new Lobby(paramUser, s, is, os);
lobbys.addElement(localLobby);
new Thread(localLobby).start();
paramStarter = null;
}
}

Related

Why does the program close immediately after launch?

Please tell me why my program ends immediately after launch. It's a Java Telegram Bot running on my home PC. I created the project using Maven.
MainClass
public class MainClass extends TelegramWebhookBot {
BootConfig cfg = new BootConfig();
public static void main(String[] args) {
ApiContextInitializer.init();
TelegramBotsApi telegramBotsApi = new TelegramBotsApi();
try {
telegramBotsApi.registerBot(new MainClass());
} catch (TelegramApiException ex) {
ex.printStackTrace();
}
}
#Override
public BotApiMethod onWebhookUpdateReceived(Update update) {
if (update.hasMessage() && update.getMessage().hasText()) {
SendMessage sendMessage = new SendMessage();
sendMessage.setChatId(update.getMessage().getChatId().toString());
sendMessage.setText("Well, all information looks like noise until you break the code.");
return sendMessage;
}
return null;
}
#Override
public String getBotUsername() {
return cfg.WEBHOOK_USER;
}
#Override
public String getBotToken() {
return cfg.WEBHOOK_TOKEN;
}
#Override
public String getBotPath() {
return cfg.WEBHOOK_USER;
}
}
BootConfig class:
public class BootConfig {
public static final String WEBHOOK_TOKEN = "SECRET";
public static final String WEBHOOK_USER = "archopobbkbot";
Console output:
Process finished with exit code 0

Java client-server increment and decrement client count

I'm trying to teach myself Java programming. Currently I am working on some client-server code. My objective is to increment the client count before the thread is launched, and decrement the count when the thread completes. Right now, the thread just sleeps for a few seconds. You can see the full directions here:
http://archive.oreilly.com/oreillyschool/courses/java5/Homework/Projects/serverEssentials_proj.project.html
Here is the code I currently have:
RepositoryServer.java
package server;
import java.io.*;
import java.net.*;
public class RepositoryServer {
ServerSocket serverSocket = null;
int state = 0;
public void bind() throws IOException {
serverSocket = new ServerSocket(9172);
state=1;
}
public void process() throws IOException {
while (state ==1) {
Socket client = serverSocket.accept();
new RepositoryThread(client).start();
}
shutdown();
}
void shutdown() throws IOException {
if (serverSocket != null) {
serverSocket.close();
serverSocket=null;
state=0;
}
}
}
RepositoryClient.java
package client;
import java.io.*;
import java.net.*;
public class RepositoryClient {
public static void main(String[] args) throws Exception {
Socket server = new Socket("localhost", 9172);
PrintWriter toServer = new PrintWriter (server.getOutputStream(),true);
BufferedReader fromServer = new BufferedReader (new InputStreamReader(server.getInputStream()));
for (int num=0; num<3; num++) {
toServer.println("SIZE");
if (!toServer.checkError()) {
int response = Integer.valueOf(fromServer.readLine());
String value = fromServer.readLine();
if (response==0) {
System.out.println(num + ": Number of Images: "+ value);
} else if (response==-1) {
System.err.println(value);
} else {
System.err.println("Received unknown response: " +response);
}
}
}
server.close();
}
}
RepositoryThread.java
package server;
import java.io.*;
import java.net.*;
public class RepositoryThread extends Thread {
Socket client;
BufferedReader fromClient;
PrintWriter toClient;
RepositoryThread (Socket s) throws IOException {
fromClient = new BufferedReader(new InputStreamReader(s.getInputStream()));
toClient=new PrintWriter(s.getOutputStream(), true);
client = s;
}
public void run() {
try {
while (true) {
String request = fromClient.readLine();
if (request == null) {
break;
}
if (request.equals("SIZE")) {
output("0");
} else {
//internal server error. Try to continue and keep processing
outputError("Unable to process request: "+ request);
continue;
}
}
} catch (IOException ioe) {
System.err.println("Thread processing terminated: " + ioe.getMessage());
}
try {
fromClient.close();
toClient.close();
client.close();
} catch (IOException ioe) {
System.err.println("Unable to close connection: " +ioe.getMessage());
}
}
void output(String result) {
toClient.println(0);
toClient.println(result);
}
void outputError(String error) {
toClient.println(-1);
toClient.println(error);
}
}
ServerLauncher.java
package server;
public class ServerLauncher {
public static RepositoryServer create() throws Exception {
RepositoryServer server = new RepositoryServer();
server.bind();
return server;
}
public static void main(String[] args) throws Exception {
RepositoryServer server = create();
System.out.println("Server awaiting client connections");
server.process();
System.out.println("Server shutting down.");
}
}
TestServer.java
package server;
import java.io.*;
import client.*;
import junit.framework.TestCase;
public class TestServer extends TestCase {
static int clientCount =0;
public void testMultipleClients() throws Exception {
RepositoryServer server = launchServer();
System.out.println(clientCount);
launchClient();
System.out.println(clientCount);
launchClient();
System.out.println(clientCount);
launchClient();
System.out.println(clientCount);
//wait until everything done.
//isClientCountZero();
Thread.sleep(10000);
server.shutdown();
assertEquals(0, server.state);
}
public static void launchClient() {
//incrementClientCount();
new Thread() {
public void run() {
try {
RepositoryClient.main(new String[]{});
} catch (Exception e) {
System.err.println("Unable to launch test client.");
}
}
}.start();
//decrementClientCount();
}
public static RepositoryServer launchServer() throws Exception {
final RepositoryServer server = ServerLauncher.create();
assertEquals(1, server.state);
new Thread() {
public void run() {
try {
server.process();
} catch (IOException ioe) {
System.err.println("Server completed");
}
}
}.start();
Thread.sleep(2000);
return server;
}
public static synchronized boolean isClientCountZero(){
if (clientCount==0) {
return true;
} else {
return false;
}
}
public static synchronized void decrementClientCount(){
clientCount--;
}
public static synchronized void incrementClientCount(){
clientCount++;
}
}
The code in question is in TestServer.java. When the Thread.sleep() methods are active, the server outputs text as expected. However, when the Thread.sleep() methods are commented out and replaced with the increment, decrement, and clientCount methods, it no longer outputs any text, just 'Server Completed'. What is my wrong with my solution to the posted link?
Thank you

WorkStealingPool exits unexpectedly

I submitted some Runnables to an ExecutorService. Inside these Runnables, wait() and notify() are called. The code works with newFixedThreadPool as the ExecutorService. With newWorkStealingPool, the process exits unexpectedly without any error message.
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
// For regular expressions
import java.util.regex.Matcher;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;
import java.util.*;
import java.util.concurrent.*;
public class TestPipeline {
public static void main(String[] args) {
runAsThreads();
}
private static void runAsThreads() {
final BlockingQueue<String> urls = new OneItemQueue<String>();
final BlockingQueue<Webpage> pages = new OneItemQueue<Webpage>();
final BlockingQueue<Link> refPairs = new OneItemQueue<Link>();
final BlockingQueue<Link> uniqRefPairs = new OneItemQueue<Link>();
final ExecutorService executor = Executors.newWorkStealingPool(6);
// final ExecutorService executor = Executors.newFixedThreadPool(6);
executor.submit(new UrlProducer(urls));
executor.submit(new PageGetter(urls, pages));
executor.submit(new LinkScanner(pages,refPairs));
executor.submit(new Uniquifier<Link>(refPairs,uniqRefPairs));
executor.submit(new LinkPrinter(uniqRefPairs));
}
}
class UrlProducer implements Runnable {
private final BlockingQueue<String> output;
public UrlProducer(BlockingQueue<String> output) {
this.output = output;
}
public void run() {
System.out.println("in producer");
for (int i=0; i<urls.length; i++)
output.put(urls[i]);
}
private static final String[] urls =
{ "http://www.itu.dk", "http://www.di.ku.dk", "http://www.miele.de",
"http://www.microsoft.com", "http://www.cnn.com", "http://www.dr.dk",
"http://www.vg.no", "http://www.tv2.dk", "http://www.google.com",
"http://www.ing.dk", "http://www.dtu.dk", "http://www.bbc.co.uk"
};
}
class PageGetter implements Runnable {
private final BlockingQueue<String> input;
private final BlockingQueue<Webpage> output;
public PageGetter(BlockingQueue<String> input, BlockingQueue<Webpage> output) {
this.input = input;
this.output = output;
}
public void run() {
while (true) {
System.out.println("in pagegetter");
String url = input.take();
// System.out.println("PageGetter: " + url);
try {
String contents = getPage(url, 200);
output.put(new Webpage(url, contents));
} catch (IOException exn) { System.out.println(exn); }
}
}
public static String getPage(String url, int maxLines) throws IOException {
// This will close the streams after use (JLS 8 para 14.20.3):
try (BufferedReader in
= new BufferedReader(new InputStreamReader(new URL(url).openStream()))) {
StringBuilder sb = new StringBuilder();
for (int i=0; i<maxLines; i++) {
String inputLine = in.readLine();
if (inputLine == null)
break;
else
sb.append(inputLine).append("\n");
}
return sb.toString();
}
}
}
class Uniquifier<T> implements Runnable{
private final Set<T> set = new HashSet<T>();
private final BlockingQueue<T> input;
private final BlockingQueue<T> output;
public Uniquifier(BlockingQueue<T> input, BlockingQueue<T> output){
this.input = input;
this.output = output;
}
public void run(){
while(true){
System.out.println("in uniquifier");
T item = input.take();
if(!set.contains(item)){
set.add(item);
output.put(item);
}
}
}
}
class LinkScanner implements Runnable {
private final BlockingQueue<Webpage> input;
private final BlockingQueue<Link> output;
public LinkScanner(BlockingQueue<Webpage> input,
BlockingQueue<Link> output) {
this.input = input;
this.output = output;
}
private final static Pattern urlPattern
= Pattern.compile("a href=\"(\\p{Graph}*)\"");
public void run() {
while (true) {
System.out.println("in link scanner");
Webpage page = input.take();
// System.out.println("LinkScanner: " + page.url);
// Extract links from the page's <a href="..."> anchors
Matcher urlMatcher = urlPattern.matcher(page.contents);
while (urlMatcher.find()) {
String link = urlMatcher.group(1);
output.put(new Link(page.url, link));
}
}
}
}
class LinkPrinter implements Runnable {
private final BlockingQueue<Link> input;
public LinkPrinter(BlockingQueue<Link> input) {
this.input = input;
}
public void run() {
while (true) {
System.out.println("in link printer");
Link link = input.take();
// System.out.println("LinkPrinter: " + link.from);
System.out.printf("%s links to %s%n", link.from, link.to);
}
}
}
class Webpage {
public final String url, contents;
public Webpage(String url, String contents) {
this.url = url;
this.contents = contents;
}
}
class Link {
public final String from, to;
public Link(String from, String to) {
this.from = from;
this.to = to;
}
// Override hashCode and equals so can be used in HashSet<Link>
public int hashCode() {
return (from == null ? 0 : from.hashCode()) * 37
+ (to == null ? 0 : to.hashCode());
}
public boolean equals(Object obj) {
Link that = obj instanceof Link ? (Link)obj : null;
return that != null
&& (from == null ? that.from == null : from.equals(that.from))
&& (to == null ? that.to == null : to.equals(that.to));
}
}
// Different from java.util.concurrent.BlockingQueue: Allows null
// items, and methods do not throw InterruptedException.
interface BlockingQueue<T> {
void put(T item);
T take();
}
class OneItemQueue<T> implements BlockingQueue<T> {
private T item;
private boolean full = false;
public void put(T item) {
synchronized (this) {
while (full) {
try { this.wait(); }
catch (InterruptedException exn) { }
}
full = true;
this.item = item;
this.notifyAll();
}
}
public T take() {
synchronized (this) {
while (!full) {
try { this.wait(); }
catch (InterruptedException exn) { }
}
full = false;
this.notifyAll();
return item;
}
}
}
Because the Pool is allocating threads dynamically, there are no threads alive after runAsThreads exits because that's the end of the main thread. There needs to be at least on thread running to keep the application alive. Adding a call to awaitTermination is needed. It's not needed for the fixed pool because that will always have active threads until it is explicitly shut down as noted in the JavaDocs.

unable to fetch process time using sigar

import java.io.IOException;
import org.hyperic.sigar.*;
public class SigarDemo {
public static void main(String args[]) throws SigarException, IOException
{
final Sigar sigar = new Sigar();
final long[] processes = sigar.getProcList();
ProcTime pt=new ProcTime();
for (final long processId : processes) {
ProcUtil.getDescription(sigar, processId);
pt=sigar.getProcTime(processId);
System.out.println("---"+pt.getStartTime());
}
}
I am trying to fetch process time of each process using sigar. I am getting this errors:
Exception in thread "main" java.lang.ExceptionInInitializerError
at taskmanager.SigarDemo.main(SigarDemo.java:22)
Caused by: java.security.AccessControlException: access denied ("java.util.PropertyPermission" "sigar.nativeLogging" "read")
at java.security.AccessControlContext.checkPermission(AccessControlContext.java:457)
at java.security.AccessController.checkPermission(AccessController.java:884)
at java.lang.SecurityManager.checkPermission(SecurityManager.java:549)
at java.lang.SecurityManager.checkPropertyAccess(SecurityManager.java:1294)
at java.lang.System.getProperty(System.java:714)
at org.hyperic.sigar.Sigar.(Sigar.java:78)
I have tried policy file setting all permission. but still I am getting errors. I am using netbeans 8.0 . and I had already setting
-Djava.security.manager -Djava.security.policy=src/dir1/dir2/important.policy
I used this code to get the process times
public static void main(String args[]) {
try {
final Sigar sigar = new Sigar();
final long[] processes = sigar.getProcList();
ProcTime pt = new ProcTime();
for (final long processId : processes) {
try {
ProcUtil.getDescription(sigar, processId);
pt = sigar.getProcTime(String.valueOf(processId));
System.out.println("---" + pt.getStartTime());
} catch (SigarException e) {
System.out.println("can't accessible...");
}
}
} catch (SigarException ex) {
ex.printStackTrace();
}
}
you don't want to specify the security policy file in VM arguments to get the process times. but the thing is getProcTime() will not return process times for some process ids because of SigarPermissionDeniedException.
but you will get process time for some processes without any problem.
I got this idea from a sample demo file from bindings\java\examples folder. I posted it below with slight modification. you can compile and run it to see the result(it includes the process time also)
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarProxy;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.ProcCredName;
import org.hyperic.sigar.ProcMem;
import org.hyperic.sigar.ProcTime;
import org.hyperic.sigar.ProcState;
import org.hyperic.sigar.ProcUtil;
import org.hyperic.sigar.cmd.Shell;
import org.hyperic.sigar.cmd.SigarCommandBase;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Show process status.
*/
public class Ps extends SigarCommandBase {
public Ps(Shell shell) {
super(shell);
}
public Ps() {
super();
}
protected boolean validateArgs(String[] args) {
return true;
}
public String getSyntaxArgs() {
return "[pid|query]";
}
public String getUsageShort() {
return "Show process status";
}
public boolean isPidCompleter() {
return true;
}
public void output(String[] args) throws SigarException {
long[] pids;
if (args.length == 0) {
pids = this.proxy.getProcList();
}
else {
pids = this.shell.findPids(args);
}
for (int i=0; i<pids.length; i++) {
long pid = pids[i];
try {
output(pid);
} catch (SigarException e) {
this.err.println("Exception getting process info for " +
pid + ": " + e.getMessage());
}
}
}
public static String join(List info) {
StringBuffer buf = new StringBuffer();
Iterator i = info.iterator();
boolean hasNext = i.hasNext();
while (hasNext) {
buf.append((String)i.next());
hasNext = i.hasNext();
if (hasNext)
buf.append("\t");
}
return buf.toString();
}
public static List getInfo(SigarProxy sigar, long pid)
throws SigarException {
ProcState state = sigar.getProcState(pid);
ProcTime time = null;
String unknown = "???";
List info = new ArrayList();
info.add(String.valueOf(pid));
try {
ProcCredName cred = sigar.getProcCredName(pid);
info.add(cred.getUser());
} catch (SigarException e) {
info.add(unknown);
}
try {
time = sigar.getProcTime(pid);
info.add(getStartTime(time.getStartTime()));
System.out.println("this line has executed..!!!");
} catch (SigarException e) {
info.add(unknown);
}
try {
ProcMem mem = sigar.getProcMem(pid);
info.add(Sigar.formatSize(mem.getSize()));
info.add(Sigar.formatSize(mem.getRss()));
info.add(Sigar.formatSize(mem.getShare()));
} catch (SigarException e) {
info.add(unknown);
}
info.add(String.valueOf(state.getState()));
if (time != null) {
info.add(getCpuTime(time));
}
else {
info.add(unknown);
}
String name = ProcUtil.getDescription(sigar, pid);
info.add(name);
return info;
}
public void output(long pid) throws SigarException {
println(join(getInfo(this.proxy, pid)));
}
public static String getCpuTime(long total) {
long t = total / 1000;
return t/60 + ":" + t%60;
}
public static String getCpuTime(ProcTime time) {
return getCpuTime(time.getTotal());
}
private static String getStartTime(long time) {
if (time == 0) {
return "00:00";
}
long timeNow = System.currentTimeMillis();
String fmt = "MMMd";
if ((timeNow - time) < ((60*60*24) * 1000)) {
fmt = "HH:mm";
}
return new SimpleDateFormat(fmt).format(new Date(time));
}
public static void main(String[] args) throws Exception {
new Ps().processCommand(args);
}
}

Accessing shared variables from two threads in Java

I'm building an application in Java which requires a Hashtable to be accessed from instances of two classes and both extend threads. I have declared the Hashtable in one of the two classes. I always get null when i try to access the Hashtable contents from one of the classes. The other class is able to access the contents without any problem. I thought this was a problem of concurrency control. Since these are threads of different classes we cannot use synchronized methods. Is there a way to make the Hashtable accessible from threads of both the classes?
Here are the some parts of the code of my application
This is the class which stores the HashMap:
public class DataStore {
public Map ChatWindows ;
public DataStore()
{
ChatWindows = new ConcurrentHashMap();
}
public synchronized void putWindow(String with,ChatWindow t)
{
ChatWindows.put(with,t);
notifyAll();
}
public synchronized ChatWindow getWindow(String with)
{
notifyAll();
return (ChatWindow)ChatWindows.get(with);
}
public synchronized void ChatWindowOpen(chatClient cc,String with,String msg)
{
// chatWith = with;
ChatWindow t;
System.out.println(with);
t = getWindow(with);
if(t == null)
{
t = new ChatWindow(cc,with,msg);
// th = new Thread(t);
putWindow(with, t);
// th.start();
}
else
{
t.setVisible(true);
}
}
}
Two classes which access 'ChatWindows' HashMap
public class chatClient extends javax.swing.JFrame implements
Runnable,ListSelectionListener,MouseListener,WindowListener{
static String LoginName,chatWith,msgToChatWindow;
Thread listThread=null,th,chatListen;
static Socket soc;
static DataOutputStream dout,dout1;
static DataInputStream din,din1;
DefaultListModel listModel;
ChatWindow t;
public DataStore ds;
/** Creates new form chatClient */
public chatClient(Login l,DataStore ds) {
listModel = new DefaultListModel();
initComponents();
clientList.addListSelectionListener(this);
clientList.addMouseListener(this);
addWindowListener(this);
this.LoginName=l.loginName;
soc = l.soc2;
din = l.din2;
dout = l.dout2;
dout1 = l.dout1;
din1 = l.din1;
super.setTitle(LoginName);
listThread = new Thread(this);
listThread.start();
this.ds = ds;
}
.
.
.
.
public void mouseClicked(MouseEvent e)
{
chatWith = (String)clientList.getSelectedValue();
ds.ChatWindowOpen(this,chatWith,"");
}
This class has run() method too, but that doesn't use the HashMap. This class is able to access the 'ChatWindows' properly.'ChatListenThread' class is not able to access the contents of HashMap properly.
public class ChatListenThread implements Runnable{
DataOutputStream dout1;
DataInputStream din1;
public static chatClient cc;
public static ChatWindow t;
public DataStore ds;
public ChatListenThread(Login l,DataStore ds)
{
din1 = l.din1;
dout1= l.dout1;
this.ds = ds;
}
.
.
.
.
public void run(){
while(true)
{
try{
String msgFromServer=new String();
msgFromServer = din1.readUTF();
StringTokenizer st=new StringTokenizer(msgFromServer);
String msgFrom=st.nextToken();
String MsgType=st.nextToken();
String msg = "";
while(st.hasMoreTokens())
{
msg=msg+" " +st.nextToken();
}
ds.ChatWindowOpen(cc,msgFrom,msg);
}
catch(IOException e)
{
System.out.println("Read failed");
}
}
}
}
It's possible. Take a look at Sharing data safely between two threads.
Okey, I couldn't use your code because I don't understand, what I did see was that you want something like this:
Create a empty JFrame with a JTabbedPane and start a thread that connects to a Socket
When input comes on the socket, create a ChatPanel (~JTextArea) and add it to one of the tabs
Add the ChatPanel to a Map that handles the messages from "from"
Pass the message to the newly created ChatPanel
So I did that and I'm posting the code below! Hope that you can use it!
If you like to test this, first start the TestChatServer (code below) and then the ChatSupervisor.
This is the code for the client
public class ChatSupervisor extends JFrame implements Runnable {
JTabbedPane tabs = new JTabbedPane();
Map<String, ChatPanel> chats = new ConcurrentHashMap<String, ChatPanel>();
public ChatSupervisor() {
super("Test Chat");
add(tabs, BorderLayout.CENTER);
new Thread(this).start();
}
public void run() {
Socket sock = null;
try {
sock = new Socket("localhost", 32134);
Scanner s = new Scanner(sock.getInputStream());
while (true) {
String from = s.next();
String type = s.next();
String message = s.nextLine();
getChat(from).incomingMessage(type, message);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (sock != null) try { sock.close(); } catch (IOException e) {}
}
}
public ChatPanel getChat(String from) {
if (!chats.containsKey(from))
chats.put(from, new ChatPanel(from));
return chats.get(from);
}
public static void main(String[] args) {
ChatSupervisor cs = new ChatSupervisor();
cs.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cs.setSize(400, 300);
cs.setVisible(true);
}
class ChatPanel extends JTextArea {
public ChatPanel(final String from) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
tabs.addTab(from, ChatPanel.this);
}
});
}
public void incomingMessage(final String type, final String message) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
append("[" + type + "]" + message);
append("\n");
}
});
}
}
}
This is the code for the test server:
public class TestChatServer {
public static void main(String[] args) throws Exception {
Socket s = new ServerSocket(32134).accept();
System.out.println("connected");
PrintWriter p = new PrintWriter(s.getOutputStream());
while (true) {
p.println("hello info Hello World!");
p.flush();
Thread.sleep(1000);
for (int i = 0; i < 10; i++) {
p.println("test" + i + " warn Testing for testing " + i);
p.flush();
Thread.sleep(100);
}
}
}
}

Categories