Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

nordi

chat [java]

Recommended Posts

Codigo extraido da [internet]

import java.io.*;import java.net.*;import javax.swing.*;import java.awt.*;import java.awt.event.*;import java.util.*;class ServerGUI extends MouseAdapter  {	JTextArea jta;	JFrame wholeFrame;	JPanel wholePanel;	JTextField jtfReceiver;	JButton jSend;	JButton jLogout;	JComboBox jCombo;	//DataOutputStream dos = null;	ServerGUI()  {		wholeFrame = new JFrame("ProChat");		wholePanel = (JPanel) (wholeFrame.getContentPane());		wholePanel.setLayout(new FlowLayout());		wholePanel.add(new JLabel("Text to send:"));		jta = new JTextArea("");		jta.setEditable(true);		jta.setRows(5);		jta.setColumns(20);		jta.setLineWrap(true);		jta.setWrapStyleWord(true);		wholePanel.add(jta);		wholePanel.add(new JLabel("User to send to:  "));		jtfReceiver = new JTextField("", 15);		wholePanel.add(jtfReceiver);		jSend = new JButton("Send text");		jSend.addMouseListener(new SendListener());		jCombo = new JComboBox();		jCombo.addItem("Client-to-Client");		jCombo.addItem("Client-Server-Client");		jLogout = new JButton("Sign off");		jLogout.addMouseListener(new LogoutListener());		wholePanel.add(jSend);		wholePanel.add(jLogout);		wholePanel.add(jCombo);		wholeFrame.setContentPane(wholePanel);		wholeFrame.setSize(330, 220);		wholeFrame.setLocation(285, 235);		wholeFrame.setResizable(false);		wholeFrame.addWindowListener(new ClosingListener());		wholeFrame.setVisible(true);	}	class SendListener extends MouseAdapter  {		public void mouseClicked(MouseEvent e)  {			try {				String s = jtfReceiver.getText();				if (s == null || s.length() < 6)  {					new PopupWindow("Username must be greater than 6 characters");					return;				}				for (int x = 0;  x < s.length();  x++)  {					if (s.charAt(x) == ' ')  {						new PopupWindow("Spaces cannot be present in the username");						return;					}				}				if (jCombo.getSelectedItem().equals("Client-Server-Client"))  {					System.out.println("Sending message through server");					ClientChat.sendMessage("SNDS" + jtfReceiver.getText() + " " + ClientChat.mainChat.getUsername() + " " +							   jta.getText() + "\n");				}  else  {					int k = ClientChat.mainChat.checkChannels(s);					if (k >= 0)  {						int w = ClientChat.numDigits(k);						System.out.println("w = " + w + " k = " + k);						ClientChat.sendMessage("CHAN" + w + k + jta.getText()); // w will be assumed to be between 1 and 9					}  else  {						ClientChat.sendMessage("NCHT" + jtfReceiver.getText() + " " + ClientChat.mainChat.getUsername() + " " +								   ClientChat.getNextPort() + " " + jta.getText() + "\n");  // format:  NCHT receiver thisuser portToConnect message						System.out.println("message sent");					}				}			}  catch (IOException ex)  {				System.out.println("There has been an ERROR!");				wholeFrame.dispose();			}			jta.setText("");		}	}	class LogoutListener extends MouseAdapter  {		public void mouseClicked(MouseEvent e)  {			try  {				ClientChat.sendMessage("LOGO");				System.out.println("LOGO Sent");				wholeFrame.dispose();			}  catch (IOException ex)  {				wholeFrame.dispose();			}		}	}	class ClosingListener extends WindowAdapter  {		public void windowClosing(WindowEvent e)  {			try  {				ClientChat.sendMessage("LOGO");				wholeFrame.dispose();			}  catch (IOException ex)  {				wholeFrame.dispose();			}		}	}}class PasswordGUI extends MouseAdapter  {	private String textShown = "";	JTextArea jta;	JFrame wholeFrame;	JPanel wholePanel;	JPanel topPanel;	JPanel bottomPanel;	JPanel buttonPanel;	JTextField jtfUser;	JTextField jtfPass;	JButton jSend;	JPanel jtfUserPanel;	JPanel jtfPassPanel;	JComboBox action;	PasswordGUI(String message)  {		wholeFrame = new JFrame("Password entry");		textShown = message;		wholePanel = (JPanel) (wholeFrame.getContentPane());		wholePanel.setLayout(new FlowLayout());		topPanel = new JPanel(new BorderLayout());		jta = new JTextArea(textShown);		jta.setEditable(false);		jta.setRows(3);		jta.setColumns(20);		jta.setLineWrap(true);		jta.setWrapStyleWord(true);		action = new JComboBox();		action.addItem("Login with existing account");		action.addItem("Create an account");		topPanel.add(jta, BorderLayout.NORTH);		topPanel.add(new Label("	"), BorderLayout.CENTER);		topPanel.add(action, BorderLayout.SOUTH);		wholePanel.add(topPanel);		bottomPanel = new JPanel(new BorderLayout());		jtfUser = new JTextField("", 15);		jtfPass = new JTextField("", 15);		jSend = new JButton("Proceed/Login");		jSend.addMouseListener(new ButtonListener());		buttonPanel = new JPanel(new FlowLayout());		buttonPanel.add(jSend);		jtfUserPanel = new JPanel (new FlowLayout());		jtfUserPanel.add(new Label("Username:  "));		jtfUserPanel.add(jtfUser);		jtfPassPanel = new JPanel (new FlowLayout());		jtfPassPanel.add(new Label("Password:  "));		jtfPassPanel.add(jtfPass);		bottomPanel.add(buttonPanel, BorderLayout.NORTH);		bottomPanel.add(jtfUserPanel, BorderLayout.CENTER);		bottomPanel.add(jtfPassPanel, BorderLayout.SOUTH);		wholePanel.add(bottomPanel);		wholeFrame.setContentPane(wholePanel);		wholeFrame.setSize(300, 240);		wholeFrame.setLocation(300, 250);		wholeFrame.setResizable(true);		wholeFrame.addWindowListener(new CloseListener());		wholeFrame.setVisible(true);	}	class ButtonListener extends MouseAdapter  {		public void mouseClicked (MouseEvent e)  {			System.out.println("mouse Clicked");			String user = jtfUser.getText();			String pass = jtfPass.getText();			ClientChat.mainChat.setUsername(user);			ClientChat.mainChat.setPassword(pass);			System.out.println("username/password set");			if (action.getSelectedItem().equals("Create an account"))  {				ClientChat.mainChat.setCreate("create");			}  else if (action.getSelectedItem().equals("Login with existing account"))  {				ClientChat.mainChat.setCreate("exists");			}	//		ClientChat.setProceedFromWait(true);			ClientChat.mainChat.resume();			System.out.println("proceed from wait set");			wholeFrame.dispose();		}	}	class CloseListener extends WindowAdapter  {		public void windowClosing (WindowEvent e)  {			if (!ClientChat.getProceedFromWait())  {				try  {					ClientChat.sendMessage("LOGO");					System.out.println("Exiting ProChat....");					System.exit(0);				}  catch (IOException ex)  {					System.exit(0);				}			}		}	}}class ClientThread extends Thread {	private ServerSocket ss = null;	private Socket clientConnect = null;	private boolean showing = false;	private DataOutputStream clientDOS = null;	private BufferedReader clientBR = null;	private String remoteUser = "";	private Vector messageList;	private JTextArea toReceiver = null;	private String ip = "";;	private int port = -1;	public ClientThread(boolean b, String command, String user)  {		messageList = new Vector();		if(B)  {			try  {				ss = new ServerSocket(Integer.parseInt(command));			}  catch (IOException ex)  {				System.out.println("ServerSocket could not be opened on port " + command);			}		}		remoteUser = user;		addGUI("newGUI");		showing = true;		System.out.println("constructor done!");	}	public void run()  {		System.out.println("Thread running");		boolean b = false;		if (ss != null)  {			System.out.println("ss != null");			b = true;			try {				catchConnection();			}  catch (Exception e)  {				new PopupWindow("Error connecting to " + remoteUser);				b = false;				int r = ClientChat.mainChat.checkChannels(remoteUser);				ClientChat.mainChat.channelStrings[r] = "";				ClientChat.chatlength--;			}		}  else  {			System.out.println("ss == null");			b = true;			try  {				makeConnection(ip, port);			}  catch (Exception e)  {				new PopupWindow("Error connecting to " + remoteUser);				int r = ClientChat.mainChat.checkChannels(remoteUser);				ClientChat.chatlength--;				ClientChat.mainChat.channelStrings[r] = "";				b = false;			}		}		try  {			readMessages();		}  catch (Exception e)  {			new PopupWindow("Link to " + remoteUser + " torn down");			destroy();		}	}	public void destroy()  {		try  {			int r = ClientChat.mainChat.checkChannels(remoteUser);			ClientChat.chatlength--;			ClientChat.mainChat.channelStrings[r] = "";			if (clientConnect != null)  {				clientConnect.close();			}			if (ss != null)  {				ss.close();			}		}  catch  (Exception e)  {			System.out.println(e);			e.printStackTrace();		}	}	public void catchConnection() throws IOException {//for case of server		System.out.println("Thread on port " + ss.getLocalPort() + " waiting for connection");		ss.setSoTimeout(35000);		clientConnect = ss.accept();		clientDOS = new DataOutputStream(clientConnect.getOutputStream());		clientBR = new BufferedReader(new InputStreamReader(clientConnect.getInputStream()));		System.out.println("Thread on port " + clientConnect.getLocalPort() + " received connection and caught streams");	}	public void makeConnection(String newip, int newport) throws IOException {		System.out.println("making connection");		clientConnect = new Socket(newip, newport);		clientDOS = new DataOutputStream(clientConnect.getOutputStream());		clientBR = new BufferedReader(new InputStreamReader(clientConnect.getInputStream()));		System.out.println("connection made to port " + newport + " of IP " + newip);	}	public void addGUI(String s)  {	}	public void sendMessage(String s) throws IOException {		clientDOS.writeBytes(s);		System.out.println("message = " + s);		new PopupWindow("message sent to " + remoteUser + ":  " + s.substring(4, s.length()));	}	public void readMessages() throws IOException {		System.out.println("reading messages");		while(true)  {			String s = clientBR.readLine();			System.out.println(s);			String code = s.substring(0, 4);			if (code.equals("TEXT"))  {				String message = s.substring(4, s.length());				if (message.length() > 0)  {					new PopupWindow("Message from " + remoteUser + ":  " + message);				}			}		}	}	public void setShowing(boolean B)  {		showing = b;	}	public boolean getShowing()  {		return showing;	}	public String getRemoteUser()  {		return remoteUser;	}	class SendingListener extends MouseAdapter  {		public void mouseClicked(MouseEvent e)  {			try  {				sendMessage("TEXT" + toReceiver.getText() + "\n");				System.out.println("TEXT sent");			}  catch (IOException ex)  {				new PopupWindow("There was an error sending this message to the receiver");			}		}	}	public void setPort(int newPort)  {		port = newPort;	}	public int getPort()  {		return port;	}	public String getIP()  {		return ip;	}	public void setIP(String newIP)  {		ip = newIP;	}}class PopupWindow extends MouseAdapter  {	private String message = "";	private JButton ok;	private JFrame wholeFrame;	private JTextArea jta;	private JPanel wholePanel;	public PopupWindow(String mess)  {		message = mess;		wholeFrame = new JFrame("Attention!");		wholePanel = (JPanel) (wholeFrame.getContentPane());		wholePanel.setLayout(new FlowLayout());		jta = new JTextArea(message);		jta.setEditable(false);		jta.setRows(3);		jta.setColumns(20);		jta.setLineWrap(true);		jta.setWrapStyleWord(true);		wholePanel.add(jta);		ok = new JButton("ok");		ok.addMouseListener(new PopUpCloser());		wholePanel.add(ok);		wholeFrame.setContentPane(wholePanel);		wholeFrame.setSize(250, 180);		wholeFrame.setLocation(300, 250);		wholeFrame.setResizable(false);		wholeFrame.setVisible(true);	}	class PopUpCloser extends MouseAdapter  {		public void MouseClicked(MouseEvent e)  {			wholeFrame.dispose();		}	}}public class ClientChat  {	public static int chatlength = 0;	private static int nextPort = 5555;	private static boolean proceedFromPassword = false;	private static boolean proceedFromWait = false;	public static MainThread mainChat = null;	public static void main(String [] args)  {		mainChat = new MainThread();		if (args.length > 0)  {			nextPort = Integer.parseInt(args[0]);		}		mainChat.start();	}	public static int getChatLength()  {		return chatlength;	}	public static void setChatLength(int a)  {		chatlength = a;	}	public static void setNextPort(int a)  {		nextPort = a;	}	public static int getNextPort()  {		return nextPort;	}	public static Socket getConnection(String server, int port)  {		System.out.println("in getConnection");		try  {			Socket bootConnect = new Socket(server, port);			BufferedReader br = new BufferedReader(new InputStreamReader(bootConnect.getInputStream()));			System.out.println("Reading from bootstrap node");			String s = br.readLine();			br.close();			bootConnect.close();			int connectPort = Integer.parseInt(s.substring(4, s.length()));			Socket connection = new Socket(server, connectPort);			return connection;		}  catch (UnknownHostException e)  {			return null;		}  catch (IOException e)  {			return null;		}	}	public static boolean parseStringSpaces (String s)  {		for (int x = 0;  x < s.length();  x++)  {			if (s.charAt(x) == ' ')  {				return true;			}		}		return false;	}	public static void sendMessage(String mess)  throws IOException {		System.out.println("sending message:  " + mess);		if (mess != null && mess.equals("LOGO"))  {			mainChat.sendMessage("LOGO" + "\n");		}  else if (mess != null && mess.substring(0, 4).equals("CHAN"))  {			int w = Integer.parseInt(mess.charAt(4) + "");			int k = Integer.parseInt(mess.substring(5, 6 + w - 1));			mainChat.channels[k].sendMessage("TEXT" + mess.substring(6 + w - 1, mess.length()) + "\n");		}  else if (mess != null && mess.substring(0, 4).equals("NCHT"))  {  //need to see StringTokenizer for this one			StringTokenizer str = new StringTokenizer(mess.substring(4, mess.length()));			String username = str.nextToken();			int qt = chatlength;			chatlength++;			mainChat.channelStrings[qt] = username;			System.out.println("before constructor");			mainChat.channels[qt] = new ClientThread(true, nextPort + "", username);			System.out.println("before run");			mainChat.sendMessage(mess);			mainChat.channels[qt].start();			System.out.println("after run");			nextPort++;			System.out.println("mess = " + mess);			System.out.println("username"+qt+" = " + mainChat.channels[qt]);		}  else  {			mainChat.sendMessage(mess);		}	}	public static int numDigits(int k)  {		int x = 1;		while (k%10 != k)  {			x++;			k = k/10;		}		return x;	}	public static void setProceedFromPassword(boolean B)  {		proceedFromPassword = b;	}	public static boolean getProceedFromPassword()  {		return proceedFromPassword;	}	public static void setProceedFromWait(boolean B)  {		proceedFromWait = b;	}	public static boolean getProceedFromWait()  {		return proceedFromWait;	}	public static void callMainThreadMethod(int a, String [] args)  {		if (a == 0)  {			mainChat.setUsername(args[0]);		}  else if (a == 1)  {			mainChat.setPassword(args[0]);		}  else if (a == 2)  {			mainChat.setCreate(args[0]);		}	}}class MainThread extends Thread  {	private String username = "";	private String password = "";	private int bootPort = 6999;	private String serverIP = "192.168.1.100";	private String message = "Please enter your username and password.";	private BufferedReader br;	private DataOutputStream dos;	private Socket connection = null;	private String create = "";	public ClientThread [] channels = new ClientThread [50];	public String [] channelStrings = new String [50];	public MainThread()  {		System.out.println("Main thread created");	}	public void run()  {		PasswordGUI entryTest = new PasswordGUI(message);		boolean b = false;		Socket connection = null;		try  {			while (connection == null)  {				connection = ClientChat.getConnection(serverIP, bootPort);			}			System.out.println("connected to port " + connection.getPort());			br = new BufferedReader(new InputStreamReader(connection.getInputStream()));			dos = new DataOutputStream(connection.getOutputStream());			System.out.println("Streams captured");			//proceedFromPassword = true;			while (!b) {				try  {					b = true;				//	while (!ClientChat.getProceedFromPassword())  {						waitForEntry();				//	}				}  catch (IOException e)  {					b = false;				}			}			System.out.println("Hey!  Made it past!");			ServerGUI serverComm = new ServerGUI();			String command = br.readLine();			System.out.println("command = " + command);			while(command != null && !(command.equals("OSUC")))  {				if (command != null && command.trim().substring(0, 4).equals("NCHT"))  {					int q = ClientChat.getChatLength();					ClientChat.setChatLength(q + 1);					StringTokenizer str = new StringTokenizer(command.trim().substring(4, command.length()));					String ip = str.nextToken();					String port = str.nextToken();					String username = str.nextToken();					String message = "";					while(str.hasMoreTokens())  {						message = message + " " + str.nextToken();					}					try  {						channels[q] = new ClientThread(false, "", username);						channelStrings[q] = username;						channels[q].setPort(Integer.parseInt(port));						channels[q].setIP(ip);						channels[q].start();						new PopupWindow("message from " + username + ":  " + message);					}  catch (Exception e)  {						System.out.println("Exception trying to set up socket");						e.printStackTrace();					}				}  else if (command != null && command.trim().substring(0, 4).equals("NSNT"))  {					System.out.println("in NSNT");					String username = command.substring(4, command.length());					int userChannel = checkChannels(username);					if (userChannel >= 0)  {						channelStrings[userChannel] = "";						channels[userChannel].destroy();						ClientChat.chatlength--;					}				}  else if (command != null && command.trim().substring(0, 4).equals("NTOK"))  {				}  else if (command != null && command.trim().substring(0, 4).equals("SMSG"))  {					StringTokenizer str = new StringTokenizer(command.trim().substring(4, command.length()));					String username = str.nextToken();					String message = "";					while(str.hasMoreTokens())  {						message = message + " " + str.nextToken();					}					new PopupWindow("message from " + username + ":  " + message);				}  else if (command != null && command.trim().substring(0, 4).equals("SSOK"))  {					String username = command.trim().substring(4, command.length());					new PopupWindow("server sent message to " + username);				}  else if (command != null && command.trim().substring(0, 4).equals("SNST"))  {					String username = command.trim().substring(4, command.length());					new PopupWindow("server could not send message to " + username);				}				command = br.readLine();				System.out.println("command = " + command);			}			dos.close();			br.close();			connection.close();			System.exit(0);		}  catch (IOException e)  {			System.out.println("Error reading from server.");			System.exit(0);		}	}	public void waitForEntry() throws IOException {		System.out.println("in waitForEntry");//		while (!ClientChat.getProceedFromWait())  {;	//	}		suspend();		if (!validatePassword())  {			System.out.println(username);			System.out.println(password);			PasswordGUI entryTest = new PasswordGUI(message);			throw(new IOException("password failed!"));		}		message = "";		ClientChat.setProceedFromPassword(true);	}	public boolean validatePassword() throws IOException {		System.out.println("validating password");		if (ClientChat.parseStringSpaces(username.trim()) || ClientChat.parseStringSpaces(password.trim()))  {			message = "username/password cannot contain spaces";			return false;		}		if (username.trim().length() < 6 || password.trim().length() < 6)  {			message = "username/password must be at least 6 characters";			return false;

Compartilhar este post


Link para o post
Compartilhar em outros sites

Olá!!!Sou eu de novo, acho que essa tá também incompleta, podes mandar divido tb?? ---- Outra dúvida, esse chat vai funcionar só dentro de uma rede local ou ele funciona para computadores comunicados pela internet tb???

Compartilhar este post


Link para o post
Compartilhar em outros sites

Boas pessoal!

 

também precisava muito do código completo ou o site de onde veio esta parte.

Agradecia muito se alguém pudesse ajudar.

 

Abraços

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.