Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[problem]with java tcp client and server chat
25-02-2013, 04:45 PM,
Post: #1
[problem]with java tcp client and server chat
file mytcapi
Code:
import java.io.*;
import java.net.Socket;
import java.net.ServerSocket;
import java.net.InetAddress;

public class MyTCPAPI
{
    int port;
    String address;
    ServerSocket server;
    Socket socket;
    PrintWriter pw;
    BufferedReader br;
    public MyTCPAPI(int port, String address) throws Exception
    {
        if(address.equals(""))
            server = new ServerSocket(port);
        else
        {
            InetAddress inet = InetAddress.getByName(address);
            socket = new Socket(inet,port);
        }
    }
        public void accept () throws Exception
        {
            socket = server.accept();

        }

        public void setStream () throws Exception
        {
            InputStream is = socket.getInputStream();
            br = new BufferedReader(new InputStreamReader(is));

            OutputStream os = socket.getOutputStream();
            pw = new PrintWriter(os, true);
        }
        public void sendMessage (String message) throws Exception
        {
            pw.println(message);
            //pw.close();
        }

        public String receiveMessage () throws Exception
        {
            String msg = br.readLine();
            //br.close();
            return socket.getRemoteSocketAddress()+" : "+msg.trim();
        }
}


ni myguiclient
Code:
/*
Author : Muhammad Hafidz Arief Bin Mohd Nor
Program Title : Applying GUI and custom API
Description : Apply your own API file to the GUI file.
Date : 07/02/2013
*/

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyGuiClient implements ActionListener, Runnable

    {
        //component on the center
        JTextArea ta_data;

        //component on the east
        JButton btn;

        //Components on the south
        JLabel lbl_input;
        JTextField txt_input;
        JButton btn_send;
        MyTCPAPI client;
public MyGuiClient(String title)
    {
    init(title);
    try
        {
            client = new MyTCPAPI(8080,"localhost");
            Thread t = new Thread(this);
            t.start();
        }
        catch(Exception exc){}
    }
public void run()
    {
        try
        {
            client.accept();
            for(;;)
            {
                client.setStream();
                ta_data.append(client.receiveMessage()+"\n");
            }
        }
        catch(Exception exc){}
    }


public void init(String title)
{
JFrame frame = new JFrame(title);
//Layout of JFrame
frame.setLayout(new BorderLayout());
//Size of JFrame
frame.setSize(500,400);
//Center on the computer screen
frame.setLocationRelativeTo(null);

//codes for other components
//North coding
//here
JPanel panel_north = new JPanel();
JLabel label_title = new JLabel(new ImageIcon("kpt.png"));
panel_north.add(label_title);

frame.add(panel_north, BorderLayout.NORTH);

//Center coding

JPanel panel_center = new JPanel();
//here

ta_data = new JTextArea(15,35);

JScrollPane pane = new JScrollPane(ta_data);
panel_center.add(pane);
frame.add(panel_center, BorderLayout.CENTER);

//East coding

JPanel panel_east = new JPanel(new GridLayout(8,1));
String [] btn_names = {"Save","Reset","Retrieve","Close"};
for (String btnName : btn_names)
{
//here
btn = new JButton(btnName);
btn.addActionListener(this);
panel_east.add(btn);
}

frame.add(panel_east, BorderLayout.EAST);

//South

JPanel panel_south = new JPanel(new FlowLayout());
//here
lbl_input = new JLabel("Message:");
txt_input = new JTextField(30);
btn_send = new JButton("Send");



btn_send.addActionListener(this);
panel_south.add(lbl_input);
panel_south.add(txt_input);
panel_south.add(btn_send);

frame.add(panel_south, BorderLayout.SOUTH);
frame.setVisible(true);

//keylistener
txt_input.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent evt)
{
if(evt.getKeyCode()==KeyEvent.VK_ENTER)
    {
        try
        {
        String msg = txt_input.getText().trim();
        ta_data.append(txt_input.getText()+"\n");
        client.setStream();
        client.sendMessage(msg);
        txt_input.setText("");
    }catch(Exception exc){}
    }
}
});
}

//actionlistener
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("Send"))
{
    try
    {
        String msg = txt_input.getText().trim();
    ta_data.append(txt_input.getText()+"\n");
    client.setStream();
        client.sendMessage(msg);
    txt_input.setText("");
}catch(Exception asd){}
}


if(e.getActionCommand().equals("Save"))
{
try{
FileApi api = new FileApi("log.txt");
String content = ta_data.getText();
api.writeFile(content.trim());
ta_data.setText("");
}catch(Exception asd){}
}
if(e.getActionCommand().equals("Reset"))
{
ta_data.setText("");
}
if(e.getActionCommand().equals("Retrieve"))
{
try{
FileApi api= new FileApi("log.txt");
String content = api.readFile();
ta_data.setText(content);
}catch(Exception asd){}


}

if(e.getActionCommand().equals("Close"))
{
System.exit(0);
}
}
public static void main(String ... arg)
{
MyGuiClient gui = new MyGuiClient ("Client");
}
}

Myguiserver

Code:
/*
Author : Muhammad Hafidz Arief Bin Mohd Nor
Program Title : Applying GUI and custom API
Description : Apply your own API file to the GUI file.
Date : 07/02/2013
*/

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyGuiServer implements ActionListener, Runnable

    {
        //component on the center
        JTextArea ta_data;

        //component on the east
        JButton btn;

        //Components on the south
        JLabel lbl_input;
        JTextField txt_input;
        JButton btn_send;
        MyTCPAPI server;
public MyGuiServer(String title)
    {
    init(title);
    try
        {
            server = new MyTCPAPI(8080,"localhost");
            Thread t = new Thread(this);
            t.start();
        }
        catch(Exception exc){}
    }
public void run()
    {
        try
        {
            server.accept();
            for(;;)
            {
                server.setStream();
                ta_data.append(server.receiveMessage()+"\n");
            }
        }
        catch(Exception exc){}
    }


public void init(String title)
{
JFrame frame = new JFrame(title);
//Layout of JFrame
frame.setLayout(new BorderLayout());
//Size of JFrame
frame.setSize(500,400);
//Center on the computer screen
frame.setLocationRelativeTo(null);

//codes for other components
//North coding
//here
JPanel panel_north = new JPanel();
JLabel label_title = new JLabel(new ImageIcon("kpt.png"));
panel_north.add(label_title);

frame.add(panel_north, BorderLayout.NORTH);

//Center coding

JPanel panel_center = new JPanel();
//here

ta_data = new JTextArea(15,35);

JScrollPane pane = new JScrollPane(ta_data);
panel_center.add(pane);
frame.add(panel_center, BorderLayout.CENTER);

//East coding

JPanel panel_east = new JPanel(new GridLayout(8,1));
String [] btn_names = {"Save","Reset","Retrieve","Close"};
for (String btnName : btn_names)
{
//here
btn = new JButton(btnName);
btn.addActionListener(this);
panel_east.add(btn);
}

frame.add(panel_east, BorderLayout.EAST);

//South

JPanel panel_south = new JPanel(new FlowLayout());
//here
lbl_input = new JLabel("Message:");
txt_input = new JTextField(30);
btn_send = new JButton("Send");



btn_send.addActionListener(this);
panel_south.add(lbl_input);
panel_south.add(txt_input);
panel_south.add(btn_send);

frame.add(panel_south, BorderLayout.SOUTH);
frame.setVisible(true);

//keylistener
txt_input.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent evt)
{
if(evt.getKeyCode()==KeyEvent.VK_ENTER)
    {
        try
        {
        String msg = txt_input.getText().trim();
        ta_data.append(txt_input.getText()+"\n");
        server.setStream();
        server.sendMessage(msg);
        txt_input.setText("");
    }catch(Exception exc){}
    }
}
});
}

//actionlistener
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("Send"))
{
    try
    {
        String msg = txt_input.getText().trim();
    ta_data.append(txt_input.getText()+"\n");
    server.setStream();
        server.sendMessage(msg);
    txt_input.setText("");
}catch(Exception asd){}
}


if(e.getActionCommand().equals("Save"))
{
try{
FileApi api = new FileApi("log.txt");
String content = ta_data.getText();
api.writeFile(content.trim());
ta_data.setText("");
}catch(Exception asd){}
}
if(e.getActionCommand().equals("Reset"))
{
ta_data.setText("");
}
if(e.getActionCommand().equals("Retrieve"))
{
try{
FileApi api= new FileApi("log.txt");
String content = api.readFile();
ta_data.setText(content);
}catch(Exception asd){}


}

if(e.getActionCommand().equals("Close"))
{
System.exit(0);
}
}
public static void main(String ... arg)
{
MyGuiServer gui = new MyGuiServer ("Server");
}
}

aku send message dari myguiclient x keluar kat myguiserver
harap2 sapa boleh bantu
Angry

sharing your knowledge to grow your knowledge...

and the knowledge is life not death
Reply
26-02-2013, 01:21 PM,
Post: #2
Re: [problem]with java tcp client and server chat
Firewall da off blom. Patutnye verify dlu connection ok or tak pastu br anto message.
Reply


Possibly Related Threads...
Thread Author Replies Views Last Post
  [help]problem with action listener pron3t 2 748 21-12-2013, 09:42 PM
Last Post: cupin06
  Soalan Java darknite 10 793 27-11-2013, 01:47 PM
Last Post: darknite
  soalan java. hard3 4 900 10-05-2013, 10:33 PM
Last Post: JejakaPemalu
  [help] inputfile java please click me to know more Timon 0 387 14-04-2013, 10:02 PM
Last Post: Timon
  java API Timon 3 814 09-12-2012, 09:58 PM
Last Post: lamki
  java background music library Timon 0 438 09-12-2012, 05:21 PM
Last Post: Timon
  JAVA Layout... mana 1 feveret :P 127001 7 1,662 03-12-2012, 10:32 AM
Last Post: Wushipher
  Java | MS Excell 127001 5 1,031 29-07-2012, 12:41 AM
Last Post: lamki
  Tutorial: Menghubungkan SQLite Dengan Java s3m00t 4 1,275 25-07-2012, 02:40 AM
Last Post: s3m00t
  array problem in GUI th3phantom 1 797 03-05-2012, 09:01 PM
Last Post: cupin06

Forum Jump: