TBD.my

Full Version: [problem]with java tcp client and server chat
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
Firewall da off blom. Patutnye verify dlu connection ok or tak pastu br anto message.