Team Project Week Fourth

Source: Internet
Author: User

Chat system design with the common site design has many different places, the common site design considerations factors, for example, the general site needs to enter a large number of landscaping and animation design and so on, and chat room as long as provided to meet the direct real-time chat between the visitors. Therefore, in the process of designing the chat system, we must consider the following several design points:

A chat program on the Internet is generally a server-side connection response, the user through the client program to log on to the server, you can log on the same server with users to chat, this is a connection-oriented communication process. Therefore, the program in the TCP/IP environment, the implementation of server-side and the client two parts of the program.

1. First, the server interface is constructed by inheriting the JFrame class.

2. Design a client program to enable it to perform normal communication functions

3. Design the listener to display the IP address port number of the login, as well as the user nickname, through the Listening button can invoke the client program, to implement the chat function.

The following is the source code:

(1) Actionprocess.java

Package chat;

Import java.awt.event.ActionEvent;

Import Java.io.DataInputStream;

Import Java.io.DataOutputStream;

Import java.io.IOException;

Import java.net.*;

Import Javax.swing.JOptionPane;

public class Actionprocess implements Runnable {

Private ChatClient client;

String name= "";

String sendtoname= "";

String sendtoid;

String filename= "";

String filepath= "";

Public actionprocess (ChatClient client) {

This.client=client;

}

public void Action (ActionEvent e) throws exception{

if (E.getsource () ==client.connection)

{

Try

{

if (client.socket.isConnected ()) {}

Else

{

String addr=joptionpane.showinputdialog ("Please enter server IP:");

InetAddress address=inetaddress.getbyname (addr);

Inetsocketaddress socketaddress=new inetsocketaddress (address,5555);

Client.socket.connect (socketaddress);

Client.in=new DataInputStream (Client.socket.getInputStream ());

Client.out=new DataOutputStream (Client.socket.getOutputStream ());

Name=client.inputname.gettext ();

Client.out.writeUTF ("The name of" +name+ "friend is on the line ...");

Client.listen.setEnabled (TRUE);

Client.filesend.setEnabled (TRUE);

Client.sendtoall.setEnabled (TRUE);

Client.sendtoone.setEnabled (TRUE);

Client.emote.setEnabled (TRUE);

if (! ( Client.thread.isAlive ()))

Client.thread=new thread (this);

Client.thread.start ();

}

}

catch (IOException ee) {}

}

if (E.getsource () ==client.listen)

{

Try

{

Name=client.inputname.gettext ();

Client.out.writeUTF ("A friend named +name+" is listening ... ");

Filesendserver filesendserver=new filesendserver ();

Filesendserver.filereceive ();

}

catch (Exception ee) {

Ee.printstacktrace ();

}

}

if (E.getsource () ==client.filesend) {

if (client.socket.isConnected ())

try {

Filesendclient filesendclient=new filesendclient ();

Filesendclient.filesend ();

Client.out.writeUTF ("Successfully send file! ");

}catch (Exception ee) {}

}

if (E.getsource () ==client.exit)

{

if (client.socket.isConnected ())

try {

Name=client.inputname.gettext ();

Client.out.writeUTF ("The name of" +name+ "friend sadly offline ...");

Client.out.flush ();

Client.out.close ();

Client.socket.close ();

} catch (IOException E1) {

E1.printstacktrace ();

}

System.exit (0);

}

String Em=client.emote.getselecteditem (). toString ();

if (Em.equals ("expression")) {

EM = "";

} else {

EM + = "on";

}

if (E.getsource () ==client.sendtoall)

{

if (client.socket.isConnected ()) {

Name=client.inputname.gettext ();

String S=client.inputcontent.gettext ();

if (s!=null)

{

Try

{

Client.out.writeUTF (name+em+ "said to everyone:" +s);

Client.out.flush ();

Client.inputContent.setText ("");

}

catch (IOException E1) {}

}

}

}

if (E.getsource () ==client.sendtoone)

{

if (client.socket.isConnected ()) {

Sendtoid=joptionpane.showinputdialog ("Please enter the ID:");

Sendtoname=joptionpane.showinputdialog ("Please enter the name of the other person:");

String S=client.inputcontent.gettext ();

Name=client.inputname.gettext ();

if (s!=null)

{

Try

{

Client.out.writeUTF (name+ "quietly" +em+ "to <" +sendtoid+ ">" +sendtoname+ "said:" +s ";

Client.out.flush ();

Client.inputContent.setText ("");

}

catch (IOException E1) {}

}

}

}

}

public void Run ()

{

String S=null;

while (true)

{

Try

{

S=client.in.readutf ();

Client.chatResult.append ("\ n" +s);

}

catch (IOException E)

{

Client.chatResult.setText ("Disconnect from server");

Try

{

Client.socket.close ();

}

catch (Exception EP) {}

Break

}

}

}

}

(2) Clicent.java

Package chat;

Import java.awt.*;

Import java.io.*;

Import java.net.*;

Import java.awt.event.*;

Import javax.swing.*;

public class Client {

public static void Main (String args[])

{

New ChatClient ();

}

}

Class ChatClient extends Frame implements ActionListener, runnable{

Private static final long serialversionuid = -4149839042245330513l;

Public Button Listen,connection,sendtoall,sendtoone,exit,filesend;

Public JComboBox emote;

Public TextField inputname,inputcontent;

Public TextArea Chatresult;

Public Socket Socket=null;

Public DataInputStream In=null;

Public DataOutputStream Out=null;

public thread thread;

ChatClient ()

{

Socket=new Socket ();

Box Box1=box.createhorizontalbox ();

Listen=new button ("Listen as Server");

Connection=new button ("Connection Server");

Filesend=new button ("Send File");

Exit=new button ("Exit");

Sendtoall=new button ("group chat");

Sendtoone=new button ("Private chat");

Listen.setenabled (FALSE);

Filesend.setenabled (FALSE);

Sendtoall.setenabled (FALSE);

Sendtoone.setenabled (FALSE);

Inputname=new TextField (6);

Inputname.setbackground (New Color (162,231,250));

Inputcontent=new TextField (22);

Inputcontent.setbackground (New Color (162,231,250));

chatresult= New TextArea ("", 17,20,textarea.scrollbars_vertical_only);

Chatresult.setbackground (New Color (162,231,250));

JLabel jlname=new JLabel ("input nickname");

Box1.add (Jlname);

Box1.add (InputName);

Box1.add (listen);

Box1.add (connection);

Box1.add (Filesend);

Box1.add (exit);

Box Box2=box.createhorizontalbox ();

emote = new JComboBox ();

Emote.setmodel New DefaultComboBoxModel (new string[] {"Expression", "Smile", "Sweet Smile", "surprise", "hehe", "Play Cool", "hehe", "giggle", "curiosity", "wink", "grimace", " Intoxicated "," shy "," angry "," yell "," anger "," sad "," smart "," rookie "," question mark "," Laugh "," Cry "," Show Love "," moan "," think "});

Emote.setenabled (FALSE);

JLabel jlintput = new JLabel ("Enter chat content");

Box2.add (Jlintput);

Box2.add (inputcontent);

Box2.add (emote);

Box2.add (Sendtoall);

Box2.add (Sendtoone);

Listen.addactionlistener (this);

Connection.addactionlistener (this);

Filesend.addactionlistener (this);

Exit.addactionlistener (this);

Sendtoall.addactionlistener (this);

Sendtoone.addactionlistener (this);

Box Box3=box.createhorizontalbox ();

Box3.add (Chatresult);

Thread=new Thread (this);

Box Box0=box.createverticalbox ();

Box0.add (Box.createverticalstrut (10));

Box0.add (Box1);

Box0.add (Box.createverticalstrut (10));

Box0.add (BOX3);

Box0.add (Box.createverticalstrut (10));

Box0.add (BOX2);

Box0.add (Box.createverticalstrut (10));

Add (box0);

SetBounds (10,30,500,400);

SetBackground (New Color (80,212,248));

SetVisible (TRUE);

Validate ();

Addwindowlistener (New Windowadapter () {

public void windowclosing (WindowEvent e) {

System.exit (0);

try {

Socket.close ();

} catch (IOException E1) {

E1.printstacktrace ();

}

}

});

}

public void actionperformed (ActionEvent e) {

Actionprocess actionprocess=new actionprocess (this);

try {

Actionprocess.action (e);

} catch (Exception E1) {

E1.printstacktrace ();

}

}

public void Run ()

{

String S=null;

while (true) {

Try

{

S=in.readutf ();

Chatresult.append ("\ n" +s);

}

catch (IOException E)

{

Chatresult.settext ("Disconnect from server");

Try

{

Socket.close ();

} catch (Exception EP) {}

Break

}

}

}

}

(3) Chatserver.java

Package chat;

Import java.net.*;

Import java.io.*;

Import java.util.*;

public class Chatserver

{

public static void Main (string[] args) throws exception{

ServerSocket Svsocket =null;

Vector threads = new vector ();

try {

Svsocket = new ServerSocket (5555);

System.out.println ("Listening ...");

}catch (Exception ex) {

System.out.println ("Server create ServerSocket failed!");

Return

}

try{

int nid = 0;

while (true) {

Socket socket = svsocket.accept ();

System.out.println ("Accept a Client");

Serverthread st = new Serverthread (socket,threads);

St.setid (nid++);

Threads.add (ST);

New Thread (ST). Start ();

for (int i=0;i < threads.size (); i++) {

Serverthread temp = (serverthread) threads.elementat (i);

}

System.out.println ("Listen again ...");

}

}catch (Exception ex) {

SYSTEM.OUT.PRINTLN ("Server is Down");

}

}

}

Class Serverthread implements runnable{

private Vector threads;

Private socket socket = NULL;

Private datainputstream in = null;

Private DataOutputStream out = null;

private int nid;

Public Serverthread (Socket socket,vector threads) {

This.socket = socket;

This.threads = threads;

try {

in = new DataInputStream (Socket.getinputstream ());

out = new DataOutputStream (Socket.getoutputstream ());

}

catch (Exception ex) {

}

}

public void Run () {

System.out.println ("Thread is running");

try{

while (true) {

String receive = In.readutf ();

if (receive = = NULL)

Return

if (Receive.contains ("sadly offline")) {

for (int i=0;i < threads.size (); i++) {

Serverthread st = (serverthread) threads.elementat (i);

St.write ("* * *" +receive+ "* * *");

}

}

else if (Receive.contains ("On-line")) {

for (int i=0;i < threads.size (); i++) {

Serverthread st = (serverthread) threads.elementat (i);

St.write ("<" +getid () + ";:" +receive);

}

}

else if (Receive.contains ("Listening in")) {

for (int i=0;i < threads.size (); i++) {

Serverthread st = (serverthread) threads.elementat (i);

St.write ("* * *" +receive+ "* * *");

}

}

else if (Receive.contains ("say")) {

if (Receive.contains ("Everyone")) {

for (int i=0;i < threads.size (); i++) {

Serverthread st = (serverthread) threads.elementat (i);

St.write ("<" +getid () + ";:" +receive);

}

}

else{

int Temp=receive.indexof ("<");

int Temp1=receive.indexof (">");

String temps=receive.substring (TEMP+1,TEMP1);

int I=integer.parseint (TempS);

Serverthread st = (serverthread) threads.elementat (i);

St.write ("<" +getid () + ";:" +receive);

St = (serverthread) threads.elementat (GetID ());

St.write ("<" +getid () + ";:" +receive);

}

}

else{

Serverthread st = (serverthread) threads.elementat (GetID ());

St.write ("* * *" +receive+ "* * *");

}

}

}catch (Exception ex) {

Threads.removeelement (this);

Ex.printstacktrace ();

}

try{

Socket.close ();

}catch (Exception ex) {

Ex.printstacktrace ();

}

}

public void Write (String msg) {

Synchronized (out) {

try{

Out.writeutf (msg);

}catch (Exception ex) {

}

}

}

public int GetID () {

return This.nid;

}

public void SetID (int nid) {

This.nid = nid;

}

}

(4) Fliesendclient.java

Package chat;

Import Java.io.BufferedReader;

Import Java.io.File;

Import Java.io.FileInputStream;

Import Java.io.InputStreamReader;

Import Java.io.OutputStream;

Import Java.io.PrintStream;

Import Java.net.Socket;

Import Javax.swing.JOptionPane;

public class Filesendclient {

public void Filesend () throws exception{

String sendtoip=joptionpane.showinputdialog ("Please enter the other IP:");

Socket socket = new socket (SENDTOIP, 1234);

BufferedReader br = new BufferedReader (

New InputStreamReader (Socket.getinputstream ()));

PrintStream PS = new PrintStream (Socket.getoutputstream ());

File File = GetFile ();

Ps.println (File.getname ());

Ps.println (File.length ());

String msg = Br.readline ();

if ("already exists". Equals (msg)) {

Joptionpane.showmessagedialog (NULL, "File already exists, please do not upload again!");

Return

}

Long Finishlen = Long.parselong (msg);

FileInputStream fis = new FileInputStream (file);

OutputStream out = Socket.getoutputstream ();

byte[] buffer = new byte[1024];

int Len;

Fis.skip (Finishlen);

while (len = fis.read (buffer))! =-1)

Out.write (buffer, 0, Len);

Fis.close ();

Socket.close ();

}

Public File GetFile () throws exception{

File File=null;

Boolean flag=false;

while (Flag==false) {

String filepath=joptionpane.showinputdialog ("Please enter the path to upload:");

File = new file (filepath);

if (!file.exists ()) {

Joptionpane.showmessagedialog (NULL, "The path you entered does not exist, please re-enter!") ");

Flag=false;

}

else if (file.isdirectory ()) {

Joptionpane.showmessagedialog (NULL, "account for unsupported folder uploads!" Please enter a file path! ");

Flag=false;

}

else flag=true;

}

return file;

}

}

(5) Filesendserver.java

Package chat;

Import Java.io.BufferedReader;

Import Java.io.File;

Import Java.io.FileOutputStream;

Import java.io.IOException;

Import Java.io.InputStream;

Import Java.io.InputStreamReader;

Import Java.io.PrintStream;

Import Java.net.ServerSocket;

Import Java.net.Socket;

Import Java.text.SimpleDateFormat;

Import Java.util.Date;

Import Javax.swing.JOptionPane;

public class filesendserver{

public void Filereceive () throws exception{

ServerSocket serversocket = new ServerSocket (1234);

Joptionpane.showmessagedialog (NULL, "service started, bind port 1234!");

while (true) {

Socket socket = serversocket.accept ();

New Fileserverthread (socket). Start ();

}

}

}

Class Fileserverthread extends thread{

Socket socket;

Public fileserverthread (socket socket) {

This.socket = socket;

}

public void Run () {

FileOutputStream fos = null;

try {

BufferedReader br = new BufferedReader (New InputStreamReader (Socket.getinputstream ()));

PrintStream PS = new PrintStream (Socket.getoutputstream ());

String fileName = Br.readline ();

Long FileLen = Long.parselong (Br.readline ());

File dir = new file ("Upload");

Dir.mkdir ();

File File = new file (dir,filename);

if (file.exists () && file.length () = = FileLen) {

Ps.println ("already exists");

Return

}

else{

Ps.println (File.length ());

}

String time = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"). Format (new Date ());

System.out.println (Time + "" + (File.exists () "Start breakpoint Continuation:": "Start uploading File:") + File.getname ());

Long start = System.currenttimemillis ();

InputStream in = Socket.getinputstream ();

FOS = new FileOutputStream (file, true);

byte[] buffer = new byte[1024];

int Len;

while (len = in.read (buffer))! =-1) {

Fos.write (buffer, 0, Len);

if (file.length () = = FileLen)

Break

}

Fos.close ();

Long end = System.currenttimemillis ();

Time = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"). Format (new Date ());

System.out.println (Time + "+" + "Upload file end:" + file.getname () + ", Duration:" + (End-start) + "milliseconds");

Ps.println ("Upload success");

Socket.close ();

} catch (IOException e) {

if (fos! = null)

try {

Fos.close ();

} catch (IOException E1) {

E1.printstacktrace ();

}

}

}

}

Team Project Week Fourth

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.