티스토리 뷰

잡담/포트폴리오

java - 채팅프로그램

박스여우 2015. 5. 31. 14:20

 채팅프로그램

 

연습삼아 채팅프로그램과 서버를 만들어 보았습니다.

 

 

 

 

 

 

아래 소스는 마음대로 사용하셔도 좋습니다.

 

 

아래는 서버의 소스입니다.

 

import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class server_Test{
 static Socket client[] = new Socket[100];
 static Socket check;
 static int count=0,counts=0;
 static String prints;
 static boolean checkss;
 
 public static void main(String[] args) throws Exception{
  ServerSocket server = new ServerSocket(50000);
  System.out.println("서버가 실행중");
  
  while(true){
   for(int i=0; i<=99;i++){
    if(client[i]==null){
     count=i;
     System.out.println("커넥트"+count);
     break;
    }
   }
   check = server.accept();
   for(int i = 0; i<=99;i++){
   if(check == client[i]){
    checkss=true;
    break;
   }
   }
   if(checkss==false){
   client[count] = check;
   System.out.println("커넥트"+count);
   myThread t1 = new myThread(client[count], count);
   t1.start();
   counts++;
   }else{
    OutputStream ot = check.getOutputStream();
    checkss=false;
   }
  }
 }


}

 

 

 

 

 

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public class myThread extends Thread{
 String nickname;
 Socket client;
 File file;
 boolean clientconnact=false;
 int count;
 String name;
 myThread(Socket i,int c){
  client = i;
  count = c;
 }
 

 @Override
 public void run(){
  try{
  System.out.println("클라이언트가 접속을 시도합니다.");
  System.out.println("접속시도 IP:"+client.getInetAddress().getHostAddress());
  clientconnact = true;
  InputStream is = client.getInputStream();
  DataInputStream din = new DataInputStream(is);
  String command;
  OutputStream ot;
  DataOutputStream dot;
  logging();
  while(clientconnact){
   command=din.readUTF();
   System.out.println(nickname+": "+command);
   if(command.equalsIgnoreCase("exit")){
    System.out.println(client.getInetAddress().getHostAddress()+"-접속종료");
    client.close();
    server_Test.counts--;
    server_Test.client[count]=null;
    clientconnact = false;
    break;
   }else{
    for(int i = 0; i <= server_Test.counts; i++){
     if(server_Test.client[i]==null){
      continue;
     }else{
      ot = server_Test.client[i].getOutputStream();
      dot = new DataOutputStream(ot);
      dot.writeUTF(nickname+": "+command);
     }
    }
   }
   }
  } catch (Exception e) {
  }
 }
 
 
 public void logging(){
  int countsss=0;
  InputStream is;
  OutputStream ot;
  DataOutputStream dot;
  while(true){
   countsss++;
   if(countsss ==20){
    System.out.println(client.getInetAddress().getHostAddress()+"-접속종료");
    try {
    client.close();
    server_Test.counts--;
    server_Test.client[count]=null;
    clientconnact=false;
    return;
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
   System.out.println("loggong");
   if(!client.isConnected()){
    return;
   }
  try {
   File file=new File("Server.txt");
   is = client.getInputStream();
   FileInputStream fin;
   DataInputStream din = new DataInputStream(is);
   ot = client.getOutputStream();
   Scanner s;
   dot = new DataOutputStream(ot);
   String command = din.readUTF();
   String password;
   boolean idhas = false, passwordright = false,iphas = false;
   if(command.equalsIgnoreCase("login")){
    fin = new FileInputStream(file);
    s = new Scanner(fin);
    command = din.readUTF();
    password = din.readUTF();
    while(s.hasNext()){
     if(command.equalsIgnoreCase(s.next())){
      idhas = true;
      passwordright = password.equalsIgnoreCase(s.next());
      s.next();
      nickname = s.next();
      break;
     }
    }
    
    if(idhas || passwordright){
     dot.writeUTF("Login!!");
     System.out.println("Login!!");
     return;
    }else if(idhas){
     dot.writeUTF("password is wrong");
     System.out.println("password is wrong");
     continue;
    }else{
     dot.writeUTF("server don't has id!");
     System.out.println("server don't has id!");
     continue;
    }
    
   }else if(command.equalsIgnoreCase("register")){
          FileWriter file_writer = new FileWriter (file, true);
    command = din.readUTF();
    password = din.readUTF();
    fin = new FileInputStream(file);
    s = new Scanner(fin);
    while(s.hasNext()){
     if(command.equalsIgnoreCase(s.next())){
      idhas = true;
      break;
     }
     s.next();
     if(client.getInetAddress().getHostAddress().equalsIgnoreCase(s.next())){
      iphas = true;
      break;
     }
     s.next();
    }
    System.out.println("id check");
    if(idhas){
     System.out.println("Server has id!");
    }else if(iphas){
     System.out.println("Server has your ip");
    }else{
     System.out.println(command);
     file_writer.write(command+" ");
     file_writer.write(password+" ");
     file_writer.write(client.getInetAddress().getHostAddress()+" ");
     file_writer.write(client.getInetAddress().getHostAddress()+" ");
     System.out.println("ID created!");
     dot.writeUTF("ID Creadted!");
     file_writer.close();
    }
   }
   
  } catch (IOException e) {
  }
 }
 }
}

 

 

 

 

아래는 클라이언트의 소스입니다.

 

 

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public class server{
 static Socket soc;
 public static void main(String[] args) throws Exception {
  Scanner scanf = new Scanner(System.in);
  String command;
  try{
  soc = new Socket("10.156.145.23", 50000);
  InputStream in;
  OutputStream ots;
  in = soc.getInputStream();
  myThread input = new myThread(in);
  input.start();
  ots = soc.getOutputStream();
  twoThread output = new twoThread(ots);
  output.start();
  login.run();
  gui.chat();
  }catch(Exception e){
   System.err.println(e);
  }
  }
 public static void end(){
  
  try {
   soc.close();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

 

 

 

 

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class twoThread extends Thread{
 static String command=null;
 static OutputStream is;
 static DataOutputStream dout;
 static boolean print=false;
 twoThread(OutputStream iss){
  is=iss;
  dout= new DataOutputStream(is);
 }
 public void run(){
  while(true){
  }
 }
 
 public static void scanf(String test){
  command=test;
  print=true;
  try {
  dout.writeUTF(""+command);
  print=false;
  }catch(Exception e){
   
  }
 }
 
 public static int end(){
  try {
   dout.writeUTF("exit");
   System.out.println("연결종료");
   System.exit(0);
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  server.end();
  return 0;
 }
}

 

 

 

import java.io.DataInputStream;
import java.io.InputStream;

public class myThread extends Thread{
 InputStream is;
 DataInputStream din;
 myThread(InputStream iss){
  is=iss;
  din= new DataInputStream(is);
 }
 public void run(){
  String first,ln[] = new String[102];
  while(true){
   try {
    first = din.readUTF();
    gui.change(first);   
   } catch (Exception e) {
    System.out.println(e);
   }
  }

 }
}

 

 

 

 

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JLabel;
import javax.swing.JButton;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class login{
 static JFrame mains;
 private static JTextField textField;
 private static JPasswordField passwordField;
 /**
  * @wbp.parser.entryPoint
  */
 
 public static void run(){
  mains = new JFrame("Pro Lan's 회의실 접속");
  mains.getContentPane().setLayout(null);
  
  textField = new JTextField();
  textField.setBounds(152, 32, 93, 21);
  mains.getContentPane().add(textField);
  textField.setColumns(10);
  
  passwordField = new JPasswordField();
  passwordField.setBounds(152, 63, 93, 21);
  mains.getContentPane().add(passwordField);
  
  JLabel lblId = new JLabel("ID:");
  lblId.setBounds(119, 35, 21, 15);
  mains.getContentPane().add(lblId);
  
  JLabel lblPassword = new JLabel("Password:");
  lblPassword.setBounds(74, 66, 66, 15);
  mains.getContentPane().add(lblPassword);
  
  JButton button = new JButton("\uB85C\uADF8\uC778");
  button.addMouseListener(new MouseAdapter() {
   @Override
   public void mouseClicked(MouseEvent arg0) {
    twoThread.scanf("login");
    twoThread.scanf(textField.getText());
    textField.setText("");
    twoThread.scanf(passwordField.getPassword().toString());
    passwordField.setText("");
   }
  });
  button.setBounds(64, 108, 97, 23);
  mains.getContentPane().add(button);
  
  JButton btnNewButton = new JButton("\uD68C\uC6D0\uAC00\uC785");
  btnNewButton.addMouseListener(new MouseAdapter() {
   @Override
   public void mouseClicked(MouseEvent arg0) {
    twoThread.scanf("registger");
    twoThread.scanf(textField.getText());
    textField.setText("");
    twoThread.scanf(passwordField.getPassword().toString());
    passwordField.setText("");
   }
  });
  btnNewButton.setBounds(164, 108, 97, 23);
  mains.getContentPane().add(btnNewButton);
  mains.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  mains.setSize(350, 200);
  mains.setVisible(true);
 }
}

 

 

 

 

import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JFrame;
import javax.swing.JScrollBar;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.ScrollPaneConstants;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import java.awt.Color;
import java.awt.event.MouseWheelListener;
import java.awt.event.MouseWheelEvent;

 

public class gui {
 static JFrame main;
 private static JTextField textField;
 private static JLabel lblText;
 private static JButton btnNewButton;
 static JTextArea dtrpnSadfasd;
 static JScrollPane scrollPane;
 static boolean scrollpanemove;
 /**
  * @wbp.parser.entryPoint
  */
 public static void chat(){
 main = new JFrame("Pro Lan's 회의실");
 main.getContentPane().setLayout(null);
 main.setSize(450, 300);
 textField = new JTextField();
 textField.setBounds(177, 230, 245, 21);
 main.getContentPane().add(textField);
 textField.setColumns(10);
 
 lblText = new JLabel("\uC774\uACF3\uC5D0 text\uB97C \uC785\uB825\uD574\uC8FC\uC138\uC694");
 lblText.setBounds(12, 233, 165, 15);
 main.getContentPane().add(lblText);
 
 textField.addKeyListener(new KeyAdapter() {
  @Override
  public void keyPressed(KeyEvent arg0) {
   if(arg0.getKeyCode() == KeyEvent.VK_ENTER){
    String input = " "+textField.getText();
    textField.setText("");
    twoThread.scanf(input);
   }
  }
 });
 
 
 
 
 btnNewButton = new JButton("\uC811\uC18D\uC885\uB8CC");
 btnNewButton.addMouseListener(new MouseAdapter() {
  @Override
  public void mouseClicked(MouseEvent arg0) {
   twoThread.end();
  }
 });
 btnNewButton.setBounds(316, 188, 106, 32);
 main.getContentPane().add(btnNewButton);
 
 scrollPane = new JScrollPane(dtrpnSadfasd, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
 scrollPane.addMouseWheelListener(new MouseWheelListener() {
  public void mouseWheelMoved(MouseWheelEvent arg0) {
   scrollpanemove=true;
  }
 });
 
 scrollPane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {
  
  @Override
  public void adjustmentValueChanged(AdjustmentEvent arg0) {
   // TODO Auto-generated method stub
   if(scrollpanemove){
    scrollpanemove=false;
   }else{
   JScrollBar src = (JScrollBar)arg0.getSource();
   src.setValue(src.getMaximum());
   }
  }
 });
 
 scrollPane.setBounds(10, 10, 300, 215);
 main.getContentPane().add(scrollPane);

 dtrpnSadfasd = new JTextArea();
 dtrpnSadfasd.setForeground(Color.BLACK);
 dtrpnSadfasd.setEnabled(false);
 dtrpnSadfasd.setCaretPosition(dtrpnSadfasd.getText().length());
 scrollPane.setViewportView(dtrpnSadfasd);
 main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 main.setVisible(true);
 }
 
 public static void change(String i){
  dtrpnSadfasd.append("\n"+i);
  scrollPane.contains(0, 10);
 }
}

 

댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함