Java application with multiple jframe-threads - java

Hello all I am building a java application where i want to select a users from a list of users and create a new JFrame to chat with(for example a new user-to-user chatbox). I have created the new JFrame into a thread i called it ChatGUI.
I am working with Smack so each of my ChatGUI object should have a MessageListener. When i exit a chatGUI thread it should delete everyting the thread created(for example the MessegeListener) and exit without interrupting any of the other threads(with their own MessegeListeners).
public class ChatGUI extends Thread {
volatile String remoteEndJID, remoteEndName, localEndJID, localEndName;
JFrame newFrame = new JFrame();
JButton sendMessage;
JTextField messageBox;
JTextPane chatBox;
Chat chat;
ChatMessageListener cMsgListener;
XMPPConnection connection;
StyleContext sContext;
volatile LinkedList<String> msgList;
DefaultStyledDocument sDoc;
public ChatGUI(String remoteEndJID, String remoteEndName, String localEndJID, String localEndName,
XMPPConnection connection, Chat chat, boolean createdLocaly, LinkedList<String> msgList) {
this.localEndName = localEndName;
this.remoteEndJID = remoteEndJID;
this.remoteEndName = remoteEndName;
this.localEndJID = localEndJID;
this.connection = connection;
this.chat = chat;
this.msgList = msgList;
if(createdLocaly==true)
cMsgListener = new ChatMessageListener();
start();
}
public void run() {
// Set title
newFrame.setTitle(remoteEndName);
newFrame.addWindowListener( new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
JFrame frame = (JFrame)e.getSource();
stop();
}
});
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
JPanel southPanel = new JPanel();
southPanel.setLayout(new GridBagLayout());
messageBox = new JTextField(30);
messageBox.requestFocusInWindow();
sendMessage = new JButton("Invia");
sendMessage.addActionListener(new sendMessageButtonListener());
sendMessage.setContentAreaFilled(false);
newFrame.getRootPane().setDefaultButton(sendMessage);
sContext = new StyleContext();
sDoc = new DefaultStyledDocument(sContext);
chatBox = new JTextPane(sDoc);
chatBox.setEditable(false);
mainPanel.add(new JScrollPane(chatBox), BorderLayout.CENTER);
GridBagConstraints left = new GridBagConstraints();
left.anchor = GridBagConstraints.LINE_START;
left.fill = GridBagConstraints.HORIZONTAL;
left.weightx = 512.0D;
left.weighty = 1.0D;
GridBagConstraints right = new GridBagConstraints();
right.insets = new Insets(0, 10, 0, 0);
right.anchor = GridBagConstraints.LINE_END;
right.fill = GridBagConstraints.NONE;
right.weightx = 1.0D;
right.weighty = 1.0D;
southPanel.add(messageBox, left);
southPanel.add(sendMessage, right);
mainPanel.add(BorderLayout.SOUTH, southPanel);
newFrame.add(mainPanel);
newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
newFrame.setSize(470, 300);
newFrame.setVisible(true);
if(msgList != null) {
startMessageManager();
}
// Start the actual XMPP conversation
if (cMsgListener != null)
chat = connection.getChatManager().createChat(remoteEndJID, cMsgListener);
System.out.println("New chat created : " + chat.getThreadID() + " " + chat.getParticipant());
}
class sendMessageButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (messageBox.getText().length() < 1) {
// Do nothing
} else if (messageBox.getText().equals(".clear")) {
chatBox.setText("Cleared all messages\n");
messageBox.setText("");
} else {
addMessage(new ChatMessage(localEndName, remoteEndName, messageBox.getText(), true));
}
messageBox.requestFocusInWindow();
}
}
public void addMessage(ChatMessage message) {
Style style = sContext.getStyle(StyleContext.DEFAULT_STYLE);
if (message.isMine == true) {
// StyleConstants.setAlignment(style, StyleConstants.ALIGN_RIGHT);
StyleConstants.setFontSize(style, 14);
StyleConstants.setSpaceAbove(style, 4);
StyleConstants.setSpaceBelow(style, 4);
StyleConstants.setForeground(style, Color.BLUE);
try {
sDoc.insertString(sDoc.getLength(),
"(" + message.Time + ") " + message.senderName + ": " + message.body + "\n", style);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
// Send the msg to the RemoteEnd
try {
chat.sendMessage(message.body);
} catch (XMPPException e) {
e.printStackTrace();
}
messageBox.setText("");
}
if (message.isMine == false) {
// StyleConstants.setAlignment(lStyle, StyleConstants.ALIGN_LEFT);
StyleConstants.setFontSize(style, 14);
StyleConstants.setSpaceAbove(style, 4);
StyleConstants.setSpaceBelow(style, 4);
StyleConstants.setForeground(style, Color.RED);
try {
sDoc.insertString(sDoc.getLength(),
"(" + message.Time + ") " + message.senderName + ": " + message.body + "\n", style);
} catch (BadLocationException e) {
e.printStackTrace();
}
}
}
class ChatMessageListener implements MessageListener {
#Override
public void processMessage(Chat chat, Message msg) {
if (msg.getType() == Message.Type.chat) {
addMessage(new ChatMessage(remoteEndName, localEndName, msg.getBody(), false));
System.out.println("The chat with threadID " + chat.getThreadID()
+ " recevied a message from the remoteEnd " + " " + chat.getParticipant());
}
}
}
public void startMessageManager() {
Thread t = new Thread() {
public void run() {
while(true){
if(msgList.size() > 0) {
for(int i=0; i<msgList.size();i++)
addMessage(new ChatMessage(remoteEndName, localEndName, msgList.removeFirst(), false));
}
}
}
};
t.setPriority(Thread.NORM_PRIORITY);
t.start();
}
}
Problem: For now i can create a new ChatGUI for each user but when i click exit in any of the created chatGUI-threads it closes the main process and all other chatGUIs.
Apologize for bad English.

I found the solution:
Since I am using Smack 3.2.2 it does not have the capability to stop a Chat.
My JFrame exited well after using newFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); instead of using newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Related

JtextField Settext and static type

I have a Swing Form (Java). In this form I have field, for example Name1. I initialize it so:
private JTextField Name1;
In this code i'm adding JTextField Name1 into my Form:
tabbedPane.addTab("T6", null, panel, "T6");
panel.setLayout(null);
Name1.setBounds(73, 11, 674, 20);
panel.add(Name1);
Additionaly I have Button1 on my form. The event in this button is changing the value of Name1. Its work normaly.
Moreover I have a Button 2 that hiding the Tab with Name1:
tabbedPane.remove(1);
tabbedPane.repaint();
tabbedPane.revalidate();
frame.repaint();
frame.revalidate();
(And, of course, I turn on my tabpane again after this)
After all that, by the pressing the Button 4 I want to change the vlue of Name1 to some text.
But it doesn't work!!!!!! SetTex doesnt work. The field is empty.
So, if I change the Name1 declaration from
private JTextField Name1;
to
static JTextField Name1;
Yes, it works. BUT! Then I can't change the value of Name1 by using
Name1.Settext("Example");
What i have to do to make Name1 available after Button 4 pressed and changable ????
The all code is:
public class GUI {
public JTextField Name_textField;
public static void main(String[] args) {
DB_Initialize();
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI window = new GUI();
window.frame.setVisible(true);
window.frame.setResizable(false);
FirstConnect FC = window.new FirstConnect();
ConnectStatus = true;
FC.FirstEntry();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public GUI() {
CurrentEnty_textField = new JTextField();
Name_textField = new JTextField();
EntriesCountlbl = new JLabel("New label");
initialize();
EntriesCountlbl.setText(Integer.toString(EC1));
if (LoginStatus == true) {
System.out.println("LoginStatus == true");
AdminPartOn();
btnNewButton.setEnabled(false);
} else {
btnNewButton_3.setEnabled(false);
tabbedPane.setEnabledAt(1, false);
// UnableForm();
AdminPartOff();
}
}
public static void DB_Initialize() {
conn3 = con3.DoConnect();
int ID;
ArrayList<String> list = new ArrayList<String>();
String l;
String p;
list = con3.LoginFileRead();
if (list.size() == 2) {
l = list.get(0);
p = list.get(1);
System.out.println("Логин из файла = " + l);
System.out.println("Пароль из файла = " + p);
ID = con3.CRMUserRequest(conn3, l, p);
AdminPanelData = con3.CRMUserFullData(conn3, l, p);
if (ID != 0) {
System.out.println("ID Юзера = " + ID);
LoginStatus = true;
}
}
EC1 = con3.CRMQuery_EntriesCount(conn3); // запрашиваем кол-во записей
StatusTableEntriesCount = con3.CRMQueryStatus_EntriesCount(conn3);
StatusTableFromCount = con3.CRMQueryFRom_EntriesCount(conn3);
System.out.println("Entries count(Из модуля GYU): " + EC1);
if (EC1 > 0) {
CurrentEntry = 1;
System.out.println("Все ОК, текущая запись - " + CurrentEntry);
} else {
System.out.println("Выскакивает обработчик ошибок");
}
con3.Ini();
con3.CRMQuery2(conn3, EC1 + 1);
StatusColumn = con3.CRMQueryStatus(conn3, StatusTableEntriesCount);
FromColumn = con3.CRMQueryFrom(conn3, StatusTableFromCount);
}
public class FirstConnect {
public void FirstEntry() {
int CurStatus = F.GetStatus(CurrentEntry - 1);
int CurFrom = F.GetFrom(CurrentEntry - 1);
if (LoginStatus != false) {
Name_textField.setText(F.GetName(CurrentEntry - 1));
} else {
Name_textField.setText("-");
}
}
}
private void initialize() {
frame = new JFrame();
panel = new JPanel();
frame.setBounds(100, 100, 816, 649);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setBounds(10, 250, 780, 361);
frame.getContentPane().add(tabbedPane);
JPanel panel_1 = new JPanel();
tabbedPane.addTab("\u0412\u0445\u043E\u0434", null, panel_1, null);
btnNewButton = new JButton("\u0412\u0445\u043E\u0434");
btnNewButton.setBounds(263, 285, 226, 37);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int ID;
ID = con3.CRMUserRequest(conn3, LoginField.getText(), PasswordField.getText());
if (ID == 0) {
} else {
MainTab();
FirstEntry3();
}
}
});
panel_1.setLayout(null);
panel_1.add(btnNewButton);
tabbedPane.addTab("\u041A\u043B\u0438\u0435\u043D\u0442", null, panel,
"\u041A\u043E\u043D\u0442\u0430\u043A\u0442\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435 \u043A\u043B\u0438\u0435\u043D\u0442\u0430");
panel.setLayout(null);
// Name_textField = new JTextField();
Name_textField.setBounds(73, 11, 674, 20);
panel.add(Name_textField);
Name_textField.setHorizontalAlignment(SwingConstants.CENTER);
Name_textField.setColumns(10);
NextEntryButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (NextEntryButton.isEnabled() != false) {
if (CurrentEntry < EC1) {
CurrentEntry = CurrentEntry + 1;
int CurStatus = F.GetStatus(CurrentEntry - 1);
int CurFrom = F.GetFrom(CurrentEntry - 1);
Name_textField.setText(F.GetName(CurrentEntry - 1));
} else {
}
}
}
});
}
public void MainTab() {
tabbedPane.addTab("1", null, panel,
"1");
tabbedPane.setEnabledAt(1, true);
panel.setLayout(null);
}
public void FirstEntry3() {
Name_textField.setText(F.GetName(CurrentEntry - 1));
}
}

Why Windows doesn't show the same output for ImageIcon on JButton as Ubuntu?

I am trying to make an image gallery just like in the following image but Windows shows images' unnecessary background whereas in Ubuntu it shows correctly.
I use the following code...
public class CommonGalleryPanel extends JPanel implements ActionListener {
public static boolean isGallaryAllowed = false;
private int counter = 0;
private InputStream binaryStream;
private BufferedImage img;
private ImageIcon iconImg;
private JButton[] btns;
private JCheckBox[] checkBox;
private JButton nextButton;
private JButton prevButton;
private ResultSet rs;
private String imageID;
private long lastRecordWas;
private long selectedOrnamentType;
private JPanel[] panels;
private JButton okButton;
private JPanel centerPanel;
private JPanel eastPanel;
private JPanel northPanel;
private JPanel southPanel;
private JComboBox<String> itemsCombo;
private String[] itemsList;
private JButton load;
private JPanel westPanel;
private int rsLen = 0;
private int noOfRows;
private BufferedImage nextButtonImage;
private BufferedImage prevButtonImage;
private static List<Long> listOfSelectedOrnaments;
private Administrator admin;
public static List<Long> getListOfSelectedOrnaments() {
return listOfSelectedOrnaments;
}
public static void setListOfSelectedOrnaments(
List<Long> listOfSelectedOrnaments) {
CommonGalleryPanel.listOfSelectedOrnaments = listOfSelectedOrnaments;
}
public CommonGalleryPanel(Administrator admin) {
this.admin = admin;
try {
setLayout(new BorderLayout());
centerPanel = new JPanel(new FlowLayout());
eastPanel = new JPanel(new GridLayout());
westPanel = new JPanel(new GridLayout());
northPanel = new JPanel(new GridBagLayout());
southPanel = new JPanel(new GridBagLayout());
listOfSelectedOrnaments = new ArrayList<Long>();
itemsList = DatabaseHandler.getOrnamentTypesInString();
itemsCombo = new JComboBox<String>(itemsList);
load = new JButton("Load");
load.addActionListener(this);
load.setActionCommand("loadButton");
northPanel.setBackground(Color.LIGHT_GRAY);
eastPanel.setBackground(Color.LIGHT_GRAY);
westPanel.setBackground(Color.LIGHT_GRAY);
southPanel.setBackground(Color.LIGHT_GRAY);
centerPanel.setBackground(Color.GRAY);
northPanel.add(itemsCombo);
northPanel.add(new JLabel(" "));
northPanel.add(load);
northPanel.add(Box.createRigidArea(new Dimension(0, 50)));
add(northPanel, BorderLayout.NORTH);
try {
nextButtonImage = Utility
.getMyResource("/buttons/next-btn.png");
prevButtonImage = Utility.getMyResource("/buttons/pre-btn.png");
} catch (Exception ex) {
ex.printStackTrace();
}
prevButton = new JButton(new ImageIcon(
prevButtonImage.getScaledInstance(40, 100,
BufferedImage.SCALE_AREA_AVERAGING)));
prevButton.setSize(getMaximumSize());
westPanel.add(prevButton);
add(eastPanel, BorderLayout.EAST);
nextButton = new JButton(new ImageIcon(
nextButtonImage.getScaledInstance(40, 100,
BufferedImage.SCALE_AREA_AVERAGING)));
eastPanel.add(nextButton);
add(westPanel, BorderLayout.WEST);
okButton = new JButton("Demonstrate");
southPanel.add(Box.createRigidArea(new Dimension(0, 50)));
southPanel.add(okButton);
add(southPanel, BorderLayout.SOUTH);
add(centerPanel, BorderLayout.CENTER);
repaint();
revalidate();
setVisible(true);
nextButton.addActionListener(this);
okButton.addActionListener(this);
prevButton.addActionListener(this);
nextButton.setActionCommand("nextButton");
okButton.setActionCommand("okButton");
prevButton.setActionCommand("prevButton");
revalidate();
repaint();
setVisible(true);
} catch (Exception backException) {
backException.printStackTrace();
}
}
public void getImages(ResultSet rs) {
try {
rsLen = 0;
while (rs.next()) {
counter++;
rsLen++;
}
if (itemsCombo.getSelectedItem().toString().equals("EARING")) {
noOfRows = DatabaseHandler
.getRowCountOfGivenSubOrnamentType(selectedOrnamentType);
} else {
noOfRows = DatabaseHandler
.getRowCountOfGivenOrnamentType(selectedOrnamentType);
}
checkBox = new JCheckBox[noOfRows + 1];
List<String> listOfImageIds = new ArrayList<String>(counter);
rs.beforeFirst();
while (rs.next()) {
listOfImageIds.add(rs.getString(1));
}
rs.beforeFirst();
int i = 0;
centerPanel.removeAll();
btns = new JButton[10];
panels = new JPanel[10];
while (rs.next()) {
if (itemsCombo.getSelectedItem().toString().equals("EARING")) {
binaryStream = rs.getBinaryStream(2);
} else {
binaryStream = rs.getBinaryStream(2);
}
img = ImageIO.read(binaryStream);
iconImg = new ImageIcon(img.getScaledInstance(290, 180,
BufferedImage.TYPE_INT_ARGB));
btns[i] = new JButton(iconImg);
checkBox[i] = new JCheckBox();
checkBox[i].setActionCommand(String.valueOf(rs.getLong(1)));
panels[i] = new JPanel();
btns[i].setBorderPainted(false);
btns[i].setActionCommand(String.valueOf(rs.getLong(1)));
btns[i].setBackground(new Color(0, 0, 0, 0));
btns[i].addActionListener(this);
//btns[i].setOpaque(true);
panels[i].add(btns[i]);
panels[i].add(checkBox[i]);
panels[i].setBackground(Color.LIGHT_GRAY);
centerPanel.add(panels[i]);
lastRecordWas = rs.getLong(1);
System.out.println("lastRecordWas = " + lastRecordWas);
i++;
}
for (int j = 0; j < i; j++) {
final int k = j;
checkBox[j].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (checkBox[k].isSelected()) {
System.out.println("Selected image..."
+ checkBox[k].getActionCommand());
listOfSelectedOrnaments.add(Long
.parseLong(checkBox[k].getActionCommand()));
} else {
System.out.println("Deselected image..."
+ checkBox[k].getActionCommand());
listOfSelectedOrnaments.remove(Long
.parseLong(checkBox[k].getActionCommand()));
}
System.out.println("Selected items list = "
+ listOfSelectedOrnaments);
}
});
}
System.out.println("counter = " + counter);
if (rsLen == 0) {
centerPanel.add(new JLabel("No more images available...."),
BorderLayout.CENTER);
repaint();
revalidate();
}
} catch (SQLException | IOException ex) {
ex.printStackTrace();
}
add(centerPanel, BorderLayout.CENTER);
repaint();
revalidate();
setVisible(true);
}
public String getImageID() {
return imageID;
}
public void setImageID(String imageID) {
this.imageID = imageID;
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("nextButton")) {
System.out.println("next button clicked...");
rs = DatabaseHandler.getNext9ItemsByType(lastRecordWas,
selectedOrnamentType);
getImages(rs);
revalidate();
repaint();
} else if (e.getActionCommand().equals("prevButton")) {
System.out.println("prev button clicked...");
rs = DatabaseHandler.getPrev9ItemsByType(lastRecordWas,
selectedOrnamentType);
getImages(rs);
revalidate();
repaint();
} else if (e.getActionCommand().equals("okButton")) {
try {
if (listOfSelectedOrnaments.isEmpty()) {
JOptionPane
.showMessageDialog(null,
"Please Select at least any one ornament to demonstrate...");
} else {
this.admin.setListOfSelectedOrnaments(
listOfSelectedOrnaments, selectedOrnamentType);
System.out.println("list is setteled with Selected images "
+ listOfSelectedOrnaments);
this.setVisible(false);
}
} catch (Exception ee) {
ee.printStackTrace();
}
} else if (e.getActionCommand().equals("loadButton")) {
try {
this.selectedOrnamentType = DatabaseHandler
.getOrnamentIdFromOrnamentName(itemsCombo
.getSelectedItem().toString());
if (itemsCombo.getSelectedItem().toString().equals("EARING")) {
rs = DatabaseHandler.getNext9EaringsByType(0l,
this.selectedOrnamentType);
} else {
rs = DatabaseHandler.getNext9ItemsByType(0l,
this.selectedOrnamentType);
}
getImages(rs);
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
try {
System.out.println("Selected image = " + e.getActionCommand());
ImageViewer.showImage(Long.parseLong(e.getActionCommand()),itemsCombo.getSelectedItem().toString());
setImageID(e.getActionCommand());
} catch (Exception ee) {
ee.printStackTrace();
}
}
}
}
Basically it works well with Ubuntu then why not on Windows ?
Just a suggestion:
put this lines first in your Main-Method:
public static void main(String[] args)
{
String propertyName = "sun.java2d.noddraw";
System.setProperty(propertyName, "true");
propertyName = "sun.java2d.d3d";
System.setProperty(propertyName, "false");
//YOUR CODE HERE...
}
By doing this, you will TURN OFF usage of direct3D and directDraw.
You can also try to use a different LookAndFeel: (here as example MetalLookAndFeel)
public static void main(String[] args)
{
String propertyName = "sun.java2d.noddraw";
System.setProperty(propertyName, "true");
propertyName = "sun.java2d.d3d";
System.setProperty(propertyName, "false");
try
{
javax.swing.UIManager.setLookAndFeel(MetalLookAndFeel.class.getName());
}
catch (Exception ex)
{
ex.printStackTrace();
}
//YOUR CODE HERE...
}
By default, SystemLookAndFeel will return "WindowsLookAndFeel" (when using Windows)
but on Linux it will return MetalLookAndFeel (or GTKLookAndFeel).
To force Windows to use MetalLookAndFeel (instead of SystemLookAndFeel (which is WindowsLookAndFeel)), you have to use the code above!

Get the TCP/IP address, not localhost

I found this code in the book Java 2 : Exam Guide by Barry Boone and William R Stanek.
This code is giving me the internal IP 127.0.0.1
But I want something like 115.245.12.61.
How could I get this.
I am providing my code below
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
public class SingleChat extends Panel {
Socket sock;
TextArea ta_RecText;
private GridBagConstraints c;
private GridBagLayout gridBag;
private Frame frame;
private Label label;
public int port = 5001;
private TextField tf_Send;
private DataOutputStream remoteOut;
static String szUserName = "";
public static void main (String [] args){
final Frame f = new Frame("Waiting For Connection...");
String s = null;
Color fore , back;
fore = new java.awt.Color(255, 255, 255);
back = new java.awt.Color(0, 173, 232);
if (args.length > 0)
s = args[0];
SingleChat chat = new SingleChat(f);
Panel pane = new Panel(), butPane = new Panel();
Label l_Label = new Label("//RADconnect");
l_Label.setForeground(fore);
l_Label.setBackground(back);
l_Label.setFont(new java.awt.Font("Lucida Console", 0, 24));
pane.add(l_Label);
f.setForeground(fore);
f.setBackground(back);
f.add("North", pane);
f.add("Center", chat);
Button but = new Button("EXIT");
but.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
f.dispose();
System.exit(0);
}
});
but.setBackground(fore);
but.setForeground(back);
butPane.add(but);
f.add("South", butPane);
f.setSize(450, 350);
f.show();
if (s == null){
chat.server();
}
else{
chat.client(s);
}
}
public SingleChat (Frame f){
frame = f;
frame.addWindowListener(new WindowExitHandler());
Insets insets = new Insets (10, 20, 5, 10);
gridBag = new GridBagLayout();
setLayout(gridBag);
c = new GridBagConstraints();
c.insets = insets;
c.gridx = 0;
c.gridx = 0;
label = new Label("Text To Send:");
gridBag.setConstraints(label, c);
add(label);
c.gridx = 1;
tf_Send = new TextField(40);
tf_Send.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
try{
//Intercept Messages And Send Them
String msg = tf_Send.getText();
remoteOut.writeUTF(szUserName+": "+msg);
tf_Send.setText("");
ta_RecText.append(szUserName+": "+msg+"\n");
} catch (IOException x) {
displayMsg(x.getMessage()+": Connection to Peer Lost");
}
}
});
gridBag.setConstraints(tf_Send, c);
add(tf_Send);
c.gridy = 1;
c.gridx = 0;
label = new Label("Text Recived:");
gridBag.setConstraints(label, c);
add(label);
c.gridx = 1;
ta_RecText = new TextArea(5, 40);
gridBag.setConstraints(ta_RecText, c);
add(ta_RecText);
ta_RecText.setForeground(Color.BLACK);
tf_Send.setForeground(Color.BLACK);
}
private void server(){
ServerSocket sv_Sock = null;
try {
InetAddress sv_Addr = InetAddress.getByName(null);
displayMsg("Waiting For Connection on "+sv_Addr.getHostAddress()+":"+port);
sv_Sock = new ServerSocket(port, 1);
sock = sv_Sock.accept();
displayMsg("Accepted Connection From "+sock.getInetAddress().getHostName());
remoteOut = new DataOutputStream(sock.getOutputStream());
new SingleChatRecive(this).start();
} catch (IOException x){
displayMsg(x.getMessage()+": Falied to connect to client");
}
finally {
if (sv_Sock != null){
try{
sv_Sock.close();
} catch (IOException x){
}
}
}
}
private void client(String sv_Name){
try {
if (sv_Name.equals("local")){
sv_Name = null;
}
InetAddress sv_Addr = InetAddress.getByName(sv_Name);
sock = new Socket(sv_Addr.getHostName(), port);
remoteOut = new DataOutputStream(sock.getOutputStream());
displayMsg("Connected to Server "+sv_Addr.getHostName()+":"+sock.getPort());
new SingleChatRecive(this).start();
} catch (IOException e){
displayMsg(e.getMessage()+": Failed to connect to server");
}
}
void displayMsg(String sz_Title){
frame.setTitle(sz_Title);
}
protected void finalize() throws Throwable {
try {
if (remoteOut != null){
remoteOut.close();
}
if (sock != null){
sock.close();
}
} catch (IOException e){
}
super.finalize();
}
class WindowExitHandler extends WindowAdapter{
public void windowClosing(WindowEvent e){
Window w = e.getWindow();
w.setVisible(false);
w.dispose();
System.exit(0);
}
}
void saveData(){
}
}
class SingleChatRecive extends Thread {
private SingleChat chat;
private DataInputStream remoteIn;
private boolean listening = true;
public SingleChatRecive(SingleChat chat){
this.chat = chat;
}
public synchronized void run(){
String s;
try {
remoteIn = new DataInputStream(chat.sock.getInputStream());
while (listening) {
s = remoteIn.readUTF();
chat.ta_RecText.append(s+"\n");
}
} catch (IOException e){
chat.displayMsg(e.getMessage()+": Connection to Peer Lost!");
} finally {
try {
if (remoteIn != null) {
remoteIn.close();
}
} catch (IOException e){
}
}
}
}
What changes could be done to avoid getting 127.0.0.1
THANKS
From your code:
InetAddress sv_Addr = InetAddress.getByName(null);
From the javadoc: "If the host is null then an InetAddress representing an address of the loopback interface is returned."
The IP address of the loopback interface is 127.0.0.1.
To get other IP addresses you must exchange null with a valid host name. Your local machine name could do if that is where you are running your server, but any valid host name should work.
InetAddress sv_Addr = InetAddress.getByName("myserver.mydomain.com");

Java Messenger Socket

I am attempting to make a "messenger"(just for learning really) and am pretty new to Socket/ServerSocket and am currently stuck in making the networking part.
Also, I do know that the ClientNetworking isn't complete. I have tried to finish it but I am stumped.
ServerMain:
public class ServerMain extends JFrame {
int WIDTH = 480;
int HEIGHT = 320;
String writeToConsole;
JPanel mainPanel, userPanel, consolePanel;
JTabbedPane tabbedPane;
JButton launchButton;
JTextArea console;
JTextField consoleInput;
JScrollPane consoleScroll;
public ServerMain() {
super("Messenger Server");
mainPanel = new JPanel();
mainPanel.setLayout(null);
Networking();
createConsolePanel();
userPanel = new JPanel();
userPanel.setLayout(null);
tabbedPane = new JTabbedPane();
tabbedPane.add(mainPanel, "Main");
tabbedPane.add(userPanel, "Users");
tabbedPane.add(consolePanel, "Console");
add(tabbedPane);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(UnsupportedLookAndFeelException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
ServerMain frame = new ServerMain();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setSize(frame.WIDTH, frame.HEIGHT);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(false);
}
public void Networking() {
ServerNetworking net;
try {
net = new ServerNetworking();
net.start();
} catch(Exception e) {
e.printStackTrace();
}
}
public void createConsolePanel() {
consolePanel = new JPanel();
consolePanel.setLayout(null);
console = new JTextArea();
console.setFont(new Font("", Font.PLAIN, 13 + 1/2));
console.setBounds(0, 0, WIDTH, HEIGHT - 100);
console.setEditable(false);
console.setLineWrap(true);
consoleInput = new JTextField(20);
consoleInput.setBounds(0, 0, WIDTH, 25);
consoleInput.setLocation(0, 240);
consoleInput.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event) {
String input = consoleInput.getText();
if(input.equalsIgnoreCase("/sendmessage")) {
//console.append(input);
console.append("Input who you would like to send the message to:");
consoleInput.setText("");
} if (input.equalsIgnoreCase("/ban")) {
console.append("Who you would like to ban");
consoleInput.setText("");
}
}
});
consolePanel.add(console);
consolePanel.add(consoleInput);
}
public void consoleWrite(String write) {
console.append(write);
}
}
ServerNetworking(Thread):
public class ServerNetworking extends Thread {
private static ServerSocket servSock;
private static final int PORT = 1234;
private static void handleClient() {
Socket link = null;
try {
link = servSock.accept();
Scanner input = new Scanner(link.getInputStream());
PrintWriter output =
new PrintWriter(link.getOutputStream(),true);
int numMessages = 0;
String message = input.nextLine();
while (!message.equals("***CLOSE***")) {
System.out.println("Message received.");
numMessages++;
output.println("Message " +
numMessages + ": " + message);
message = input.nextLine();
}
output.println(numMessages + " messages received.");
} catch(IOException ioEx) {
ioEx.printStackTrace();
} finally {
try {
System.out.println( "\n* Closing connection... *");
link.close();
} catch(IOException ioEx) {
System.out.println("Unable to disconnect!");
System.exit(1);
}
}
}
public void run() {
System.out.println("Opening port...\n");
try {
servSock = new ServerSocket(PORT);
} catch(IOException ioEx) {
System.out.println("Unable to attach to port!");
System.exit(1);
} do {
handleClient();
} while (true);
}
}
ClientMain:
public class ClientMain extends JFrame {
int WIDTH = 640;
int HEIGHT = 480;
JTabbedPane tabbedPane;
JMenuBar topMenuBar;
JMenu userMenu, helpMenu, settingsMenu;
JRadioButtonMenuItem menuItem;
JPanel mainPanel, friendsPanel, groupsPanel, testPanel;
JLabel title;
JScrollPane consoleScrollPane;
JSplitPane friendsPane;
JTextArea messageArea, testArea;
JTextField testField;
Box box;
public ClientMain() {
super("Messenger Client");
Networking();
title = new JLabel("Client!");
title.setFont(new Font("Impact", Font.PLAIN, 32));
mainPanel = new JPanel();
mainPanel.setLayout(null);
mainPanel.add(title);
groupsPanel = new JPanel();
groupsPanel.setLayout(null);
friendsPanel = new JPanel();
friendsPanel.setLayout(null);
testPanel = new JPanel();
testPanel.setLayout(null);
testArea = new JTextArea();
testArea.setFont(new Font("", Font.PLAIN, 13 + 1/2));
testArea.setBounds(0, 0, WIDTH, HEIGHT - 100);
testArea.setEditable(false);
testArea.setLineWrap(true);
testField = new JTextField(20);
testField.setBounds(0, 380, 640, 25);
//testField.setLocation(0, HEIGHT - 50);
testField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ClientNet net = new ClientNet();
String input = null;
input = testField.getText();
testArea.append(input);
testField.setText("");
if(input.equalsIgnoreCase("/sendmessage")) {
testArea.append("\n Input who you would like to send the message to:");
input = null;
if(input.equalsIgnoreCase("Hello")) {
net.userEntry = input;
}
}
}
});
testPanel.add(testArea);
testPanel.add(testField);
tabbedPane = new JTabbedPane();
tabbedPane.add(mainPanel, "Main");
tabbedPane.add(friendsPanel, "Friends");
tabbedPane.add(groupsPanel, "Groups");
tabbedPane.add(testPanel, "Test");
topMenuBar = new JMenuBar();
userMenu = new JMenu("User");
settingsMenu = new JMenu("Settings");
helpMenu = new JMenu("Help");
menuItem = new JRadioButtonMenuItem("Something here");
userMenu.add(menuItem);
topMenuBar.add(userMenu, "User");
topMenuBar.add(settingsMenu, "Settings");
topMenuBar.add(helpMenu, "Help");
add(topMenuBar);
add(tabbedPane);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(UnsupportedLookAndFeelException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
ClientMain frame = new ClientMain();
Insets insets = frame.getInsets();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setSize(frame.WIDTH, frame.HEIGHT);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(false);
frame.setJMenuBar(frame.topMenuBar);
}
public void Networking() {
ClientNet net;
try {
net = new ClientNet();
net.start();
} catch(Exception e) {
e.printStackTrace();
}
}
public void createMenuBar() {
topMenuBar = new JMenuBar();
userMenu = new JMenu("User");
settingsMenu = new JMenu("Settings");
helpMenu = new JMenu("Help");
menuItem = new JRadioButtonMenuItem("MenuItem");
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
topMenuBar.add(userMenu, "User");
topMenuBar.add(settingsMenu, "Settings");
topMenuBar.add(helpMenu, "Help");
}
public void getFriends(String username) {
}
}
ClientNetworking(Thread):
public class ClientMain extends JFrame {
int WIDTH = 640;
int HEIGHT = 480;
JTabbedPane tabbedPane;
JMenuBar topMenuBar;
JMenu userMenu, helpMenu, settingsMenu;
JRadioButtonMenuItem menuItem;
JPanel mainPanel, friendsPanel, groupsPanel, testPanel;
JLabel title;
JScrollPane consoleScrollPane;
JSplitPane friendsPane;
JTextArea messageArea, testArea;
JTextField testField;
Box box;
public ClientMain() {
super("Messenger Client");
Networking();
title = new JLabel("Client!");
title.setFont(new Font("Impact", Font.PLAIN, 32));
mainPanel = new JPanel();
mainPanel.setLayout(null);
mainPanel.add(title);
groupsPanel = new JPanel();
groupsPanel.setLayout(null);
friendsPanel = new JPanel();
friendsPanel.setLayout(null);
testPanel = new JPanel();
testPanel.setLayout(null);
testArea = new JTextArea();
testArea.setFont(new Font("", Font.PLAIN, 13 + 1/2));
testArea.setBounds(0, 0, WIDTH, HEIGHT - 100);
testArea.setEditable(false);
testArea.setLineWrap(true);
testField = new JTextField(20);
testField.setBounds(0, 380, 640, 25);
//testField.setLocation(0, HEIGHT - 50);
testField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ClientNet net = new ClientNet();
String input = null;
input = testField.getText();
testArea.append(input);
testField.setText("");
if(input.equalsIgnoreCase("/sendmessage")) {
testArea.append("\n Input who you would like to send the message to:");
input = null;
if(input.equalsIgnoreCase("Hello")) {
net.userEntry = input;
}
}
}
});
testPanel.add(testArea);
testPanel.add(testField);
tabbedPane = new JTabbedPane();
tabbedPane.add(mainPanel, "Main");
tabbedPane.add(friendsPanel, "Friends");
tabbedPane.add(groupsPanel, "Groups");
tabbedPane.add(testPanel, "Test");
topMenuBar = new JMenuBar();
userMenu = new JMenu("User");
settingsMenu = new JMenu("Settings");
helpMenu = new JMenu("Help");
menuItem = new JRadioButtonMenuItem("Something here");
userMenu.add(menuItem);
topMenuBar.add(userMenu, "User");
topMenuBar.add(settingsMenu, "Settings");
topMenuBar.add(helpMenu, "Help");
add(topMenuBar);
add(tabbedPane);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(UnsupportedLookAndFeelException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
ClientMain frame = new ClientMain();
Insets insets = frame.getInsets();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setSize(frame.WIDTH, frame.HEIGHT);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(false);
frame.setJMenuBar(frame.topMenuBar);
}
public void Networking() {
ClientNet net;
try {
net = new ClientNet();
net.start();
} catch(Exception e) {
e.printStackTrace();
}
}
public void createMenuBar() {
topMenuBar = new JMenuBar();
userMenu = new JMenu("User");
settingsMenu = new JMenu("Settings");
helpMenu = new JMenu("Help");
menuItem = new JRadioButtonMenuItem("MenuItem");
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
topMenuBar.add(userMenu, "User");
topMenuBar.add(settingsMenu, "Settings");
topMenuBar.add(helpMenu, "Help");
}
public void getFriends(String username) {
}
}
This is the error I get when I launch the server, then the client:
It shouldn't be saying "Message received" cause I don't actually send a message
Opening port...
Message received.
* Closing connection... *
Exception in thread "Thread-1" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at Server.ServerNetworking.handleClient(ServerNetworking.java:29)
at Server.ServerNetworking.run(ServerNetworking.java:53)
I think the problem is the following loop in the ServerNetworking class:
while (!message.equals("***CLOSE***")) {
System.out.println("Message received.");
numMessages++;
output.println("Message " +
numMessages + ": " + message);
message = input.nextLine();
}
The problem with this code is that after recieving the complete message from the client the last line of code
message = input.nextLine();
looks for another next line from the message, but since the message has already been consumed, it throws the following exception:
NoSuchElementException - if no line was found
So before reading for the next line you need to make sure that there is next line to be read. This you can do using the
hasNextLine()
method, which will return true if there is next line otherwise false.
if(input.hasNextLine()) {
message = input.nextLine(); // read the next line
} else {
break; // exit the loop because, nothing to read left
}

How do I get 2 computers to communicate to each other in java for an instant messenger?

I have been working on an instant messenger in only java code for a while now. I am able to get it to work only if I am running the server and the client on the same computer then they communicate. But I cant get 2 different computers to connect to the same server and communicate. I have looked at many examples and I still dont understand what needs to be changed. I will show the code below most of it can be ignored only the network part needs to be looked at. The sever connection is at the bottom of the client code. I am a beginner and I appreciate any help. Thanks.
Client Code:
import javax.swing.*;
import javax.swing.text.DefaultCaret;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.util.Date;
import java.net.*;
import java.io.*;
public class NukeChatv3 extends JFrame
{
private JTextArea showtext;
private JTextField usertext;
private String hostname;
private Socket connectionsock;
private BufferedReader serverinput;
private PrintWriter serveroutput;
private int port;
private static final long serialVersionUID = 1L;
private class entersend implements KeyListener
{
public void keyTyped ( KeyEvent e )
{
}
public void keyPressed ( KeyEvent e)
{
String text = usertext.getText();
if(e.getKeyCode()== KeyEvent.VK_ENTER)
{
if (usertext.getText().equals(""))
return;
else
{
//try{
serveroutput.println(text);
usertext.setText("");
//showtext.append("[" + ft.format(dNow) + "]" + "\n" + "UserName: " + serverdata +"\n\n");
//}
/*catch(IOException in)
{
showtext.append(in.getMessage());
}*/
}
}
else
return;
}
public void keyReleased ( KeyEvent e )
{
}
}
private class sender implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (usertext.getText().equals(""))
return;
else
{
Date dNow = new Date( );
SimpleDateFormat ft = new SimpleDateFormat ("hh:mm:ss");
String text = usertext.getText();
usertext.setText("");
//* Send message to server
showtext.append(ft.format(dNow) + "\n" + "UserName: " + text +"\n\n");
}
}
}
private class startconnection implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
clientconnection connect = new clientconnection();
connect.start();
}
}
private class CheckOnExit implements WindowListener
{
public void windowOpened(WindowEvent e)
{}
public void windowClosing(WindowEvent e)
{
ConfirmWindow checkers = new ConfirmWindow( );
checkers.setVisible(true);
}
public void windowClosed(WindowEvent e)
{}
public void windowIconified(WindowEvent e)
{}
public void windowDeiconified(WindowEvent e)
{}
public void windowActivated(WindowEvent e)
{}
public void windowDeactivated(WindowEvent e)
{}
}
private class ConfirmWindow extends JFrame implements ActionListener
{
private static final long serialVersionUID = 1L;
public ConfirmWindow( )
{
setSize(200, 100);
getContentPane( ).setBackground(Color.LIGHT_GRAY);
setLayout(new BorderLayout( ));
JLabel confirmLabel = new JLabel(
"Are you sure you want to exit?");
add(confirmLabel, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel( );
buttonPanel.setBackground(Color.GRAY);
buttonPanel.setLayout(new FlowLayout( ));
JButton exitButton = new JButton("Yes");
exitButton.addActionListener(this);
buttonPanel.add(exitButton);
JButton cancelButton = new JButton("No");
cancelButton.addActionListener(this);
buttonPanel.add(cancelButton);
add(buttonPanel, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand( );
if (actionCommand.equals("Yes"))
System.exit(0);
else if (actionCommand.equals("No"))
dispose( );
else
System.out.println("Unexpected Error in Confirm Window.");
}
}
public static void main(String[] args)
{
NukeChatv3 nuke = new NukeChatv3();
nuke.setVisible(true);
}
public NukeChatv3()
{
setTitle("NukeChat v3");
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
setSize(550, 400);
setResizable(false);
addWindowListener(new CheckOnExit());
addWindowListener(new WindowAdapter(){
public void windowOpened(WindowEvent e){
usertext.requestFocus();
}
});
getContentPane().setBackground(Color.BLACK);
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
showtext = new JTextArea(15, 35);
showtext.setEditable(false);
showtext.setLineWrap(true);
DefaultCaret caret = (DefaultCaret)showtext.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
JScrollPane scrollbar = new JScrollPane(showtext);
scrollbar.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollbar.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
c.anchor = GridBagConstraints.FIRST_LINE_START;
//c.gridwidth = 2;
c.insets = new Insets(20, 20, 20, 20);
c.weightx = .5;
c.weighty = .5;
c.gridx = 0;
c.gridy = 0;
add(scrollbar, c);
usertext = new JTextField(35);
usertext.requestFocusInWindow();
usertext.addKeyListener(new entersend());
//c.gridwidth = 1;
c.insets = new Insets(0, 20, 0, 0);
c.weightx = .5;
c.gridx = 0;
c.gridy = 1;
add(usertext, c);
JPanel empty = new JPanel();
c.gridx = 1;
c.gridy = 0;
empty.setLayout(new GridLayout(2,1));
JButton test1 = new JButton("test1");
empty.add(test1);
JButton test2 = new JButton("test2");
empty.add(test2);
add(empty, c);
JButton send = new JButton("Send");
send.addActionListener(new sender());
c.ipady = -5;
c.insets = new Insets(0, 0, 20, 0);
c.gridx = 1;
c.gridy = 1;
add(send, c);
JMenu menu = new JMenu("File");
JMenuItem connection = new JMenuItem("Connect");
connection.addActionListener(new startconnection());
menu.add(connection);
JMenuBar bar = new JMenuBar();
bar.add(menu);
setJMenuBar(bar);
}
private class clientconnection extends Thread
{
public void run()
{
try
{
// Set host name and port//
hostname = "localhost";
port = 16666;
// connect to socket of the server//
connectionsock = new Socket(hostname, port);
// set up client input from server//
serverinput = new BufferedReader(new InputStreamReader(connectionsock.getInputStream()));
// set up client output to server//
serveroutput = new PrintWriter(connectionsock.getOutputStream(), true);
// set up a looping thread to constantly check if server has sent anything
String serverdata = "";
while ((serverdata = serverinput.readLine()) != null)
{
Thread.sleep(500);
Date dNow = new Date( );
SimpleDateFormat ft = new SimpleDateFormat ("hh:mm:ss");
showtext.append("[" + ft.format(dNow) + "]" + "\n" +"Recieved from server: \n" + "UserName: " + serverdata +"\n\n");
}
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
catch(InterruptedException inter)
{
showtext.append("Unexpected interruption\n\n");
}
}
}
}
Server Code :
import java.net.ServerSocket;
import java.io.*;
import java.net.Socket;
import java.io.DataOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class servertest extends JFrame
{
private JButton start;
private JTextArea text;
private BufferedReader clientinput;
private PrintWriter clientoutput;
private class listen implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
connection connect = new connection();
connect.start();
}
}
public servertest ()
{
setSize(400,300);
setLayout(new BorderLayout());
start = new JButton("Start");
start.addActionListener(new listen());
add(start, BorderLayout.SOUTH);
text = new JTextArea(6, 10);
text.setEditable(false);
add(text, BorderLayout.CENTER);
}
private class connection extends Thread
{
public void run()
{
try
{
// Sets up a server socket with set port//
text.setText("Waiting for connection on port 16666");
ServerSocket serversock = new ServerSocket(16666);
// Waits for the Client to connect to the server//
Socket connectionsock = serversock.accept();
// Sets up Input from the Client to go to the server//
clientinput = new BufferedReader(new InputStreamReader(connectionsock.getInputStream()));
// Sets up data output to send data from server to client//
clientoutput = new PrintWriter(connectionsock.getOutputStream(), true);
// Test server to see if it can perform a simple task//
text.setText("Connection made, waiting to client to send there name");
clientoutput.println("Enter your name please.");
// Get users name//
String clienttext = clientinput.readLine();
// Reply back to the client//
String replytext = "Welcome " + clienttext;
clientoutput.println(replytext);
text.setText("Sent: " + replytext);
while ((replytext = clientinput.readLine()) != null)
{
clientoutput.println(replytext);
text.setText("Sent: " + replytext);
}
// If you need to close the Socket connections
// clientoutput.close();
// clientinput.close();
// connetionsock.close();
// serversock.close();
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
}
public static void main(String[] args)
{
servertest test = new servertest();
test.setVisible(true);
}
In your client code, specify correct hostname/IP address where server is running:
private class clientconnection extends Thread
{
public void run()
{
try
{
// Set host name and port//
hostname = "localhost"; //<---- Change this to server IP address
port = 16666;

Categories