Java使用TCP聊天程序

前面使用了UDP进行通信的聊天程序

现在做一个用TCP进行通信的聊天程序

原理:

ServerSocket Socket

1.开一个线程监听端口,准备接收消息

2.不断接受消息发送到目的端口

P.S.因为TCP是面向连接的所以中间要注意先后顺序,代码写得有点乱

  1 import java.io.IOException;
  2 import java.io.InputStream;
  3 import java.io.OutputStream;
  4 import java.net.InetAddress;
  5 import java.net.ServerSocket;
  6 import java.net.Socket;
  7 import java.util.Scanner;
  8 
  9 /**
 10  * 聊天程序
 11  * TCP实现
 12  * 开一个线程监听一个端口,接收消息
 13  * @author GXF
 14  *
 15  */
 16 public class TcpChatWindow {
 17     private int destPort;                        //目的端口
 18     private int listenPort;                        //监听端口
 19     private Socket socketToSendMessage;            //发送消息的socket
 20     
 21     public TcpChatWindow(int destPort, int listenPort){
 22         this.destPort = destPort;
 23         this.listenPort = listenPort;
 24         
 25         //init
 26         init();
 27     }
 28     
 29     /**
 30      * 接收消息线程
 31      * @author GXF
 32      *
 33      */
 34     class ReceiveMessageThread implements Runnable{
 35         //接收消息socket
 36         private ServerSocket receiveMessageSocket;
 37         
 38         @Override
 39         public void run() {
 40             //init
 41             init();
 42             while(true){
 43                 try {
 44                     Socket clientSocket = receiveMessageSocket.accept();
 45                     InputStream inputStreamOfClientSocket = clientSocket.getInputStream();
 46                     byte buff[] = new byte[1024];
 47                     int lengthOfMessage = -1;
 48                     StringBuilder sb = new StringBuilder();
 49                     //read message
 50                     while((lengthOfMessage = inputStreamOfClientSocket.read(buff)) > 0){
 51                         sb.append(new String(buff, 0, lengthOfMessage));
 52                     }//while
 53                     //输出消息到控制台
 54                     System.out.println(sb.toString());
 55                     //关闭socket
 56                     clientSocket.close();
 57                 } catch (IOException e) {
 58                     e.printStackTrace();
 59                 }
 60             }
 61         }
 62         
 63         /**
 64          * 对线程进行初始化
 65          */
 66         public void init(){
 67             try {
 68                 receiveMessageSocket = new ServerSocket(listenPort);
 69             } catch (IOException e) {
 70                 e.printStackTrace();
 71             }
 72         }
 73         
 74     }
 75     
 76     //初始化操作
 77     private void init(){
 78             
 79         //start ReceiveMessageThread
 80         Thread receiveMessageThread = new Thread(new ReceiveMessageThread());
 81         receiveMessageThread.start();
 82         //input message and send message
 83         while(true){
 84             Scanner scanner = new Scanner(System.in);
 85             String messageToSend = scanner.nextLine();
 86 //            getSocketToSendMessage();
 87             sendMessage(messageToSend);
 88             scanner.close();
 89         }
 90             
 91         
 92     }
 93     
 94     /**
 95      * 向对方发送消息
 96      * @param message
 97      */
 98     public void sendMessage(String message){
 99         try {
100             Socket socketToSendMessage = new Socket(InetAddress.getByName("127.0.0.1"), destPort);
101             OutputStream outputStreamOfClientSocket = socketToSendMessage.getOutputStream();
102             byte bytesOfMessage[] = message.getBytes();
103             outputStreamOfClientSocket.write(bytesOfMessage);
104             socketToSendMessage.close();
105         } catch (IOException e) {
106             e.printStackTrace();
107         }
108     }
109     
110     //获取发送消息的socket
111     public Socket getSocketToSendMessage(){
112         if(socketToSendMessage == null){
113             try {
114                 socketToSendMessage = new Socket(InetAddress.getByName("127.0.0.1"), destPort);
115             } catch (IOException e) {
116                 // TODO Auto-generated catch block
117                 e.printStackTrace();
118             }
119         }
120         return socketToSendMessage;
121     }
122     
123     public static void main(String args[]){
124         if(args.length != 2){
125             System.out.println("usage: java TcpChatWindow destport listenport");
126             return;
127         }
128         int destPort = Integer.valueOf(args[0]);
129         int listenPort = Integer.valueOf(args[1]);
130         
131         TcpChatWindow chatWindow = new TcpChatWindow(destPort, listenPort);
132     }
133 }

 

posted on 2015-11-02 15:59  luckygxf  阅读(658)  评论(0编辑  收藏  举报

导航