簡體   English   中英

無法發送/接收套接字消息?

[英]Can't send / receive socket messages?

我正在嘗試編程一個小的聊天控制台,因為最近我學會了使用ServerSocket和Sockets。 但是我有一個問題,我沒有收到/發送任何消息我在做什么錯?

類:聊天(主)

package chatting;

import java.util.Scanner;

public class Chatting {

public static Client client;
public static Server server;

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.print("Your username: ");
    String name = sc.nextLine();
    System.out.print("connect to: ");
    String ip = sc.nextLine();
    client = new Client(ip.split(":")[0], Integer.parseInt(ip.split(":")[1]), name);
    while (true){
        String chat = sc.nextLine();
        client.send(chat);
    }
}

}

類別:客戶

package chatting;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class Client {

Socket s;

public Client(String ip, int port, String name){
    if (ip.equalsIgnoreCase("localhost")){
        Chatting.server = new Server();
    }
    new Thread(new Runnable(){
        @Override
        public void run(){
            try{
                s = new Socket(ip, port);
                System.out.println("CONNECTION >> Waiting for conformation with name "+name+"!");
                send("#reg"+name);
                WaitForMessage("#confirmed");
                System.out.println("CONNECTION >> You have been registered to server!");
                while (true){
                    List<String> recieve = recieve();
                    if (!recieve.isEmpty()){
                        for (String str : recieve){
                            System.out.println(str);
                        }
                    }
                }
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }).start();
}

public void send(String msg){
    try{
        OutputStream os = s.getOutputStream();
        PrintWriter pw = new PrintWriter(new OutputStreamWriter(os), true);
        pw.write(msg);
        pw.flush();
    }catch(Exception e){
        e.printStackTrace();
    }
}

public List<String> recieve(){
    List<String> r = new ArrayList<String>();
    try{
        InputStream is = s.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = br.readLine())!=null){
            System.out.println("CRECIEVE >> "+line);
            r.add(line);
        }
    }catch(Exception e){
        e.printStackTrace();
    }
    return r;
}

public void WaitForMessage(String msg){
    while (true){
        if (recieve().contains(msg)) break;
    }
}
}

類別:服務器

package chatting;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class Server {

ServerSocket ss;
List<Socket> s;
HashMap<String, String> registered;

public Server(){
    s = new ArrayList<Socket>();
    registered = new HashMap<String, String>();
    try {
        ss = new ServerSocket(1234);
        System.out.println("SERVER >> created server on port 1234!");
    } catch (IOException e) {
        e.printStackTrace();
    }
    new Thread(new Runnable(){
        @Override
        public void run(){
            while (true){
                try{
                    Socket socket = ss.accept();
                    if (socket != null){
                        System.out.println("SERVER >> client connected "+socket.getLocalAddress().toString());
                        s.add(socket);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }).start();
    new Thread(new Runnable(){
        @Override
        public void run(){
            while (true){
                for (Socket s : s){
                    List<String> result = translate(recieve(s));
                    if (!result.isEmpty()){
                        for (String str : result){
                            if (str.startsWith("#reg")){
                                str = str.replaceAll("#reg", "");
                                registered.put(s.getInetAddress().toString(), str);
                                System.out.println("SERVER >> user "+str+" on "+s.getLocalAddress().toString()+" registered!");
                                send(s, "#confirmed");
                            }else{
                                sendToAll(registered.get(s.getLocalAddress().toString())+" >> "+str);
                            }
                        }
                    }
                }
            }
        }
    }).start();
}

public void send(Socket s, String str){
    try{
        OutputStream os = s.getOutputStream();
        PrintWriter pw = new PrintWriter(new OutputStreamWriter(os), true);
        pw.write(str);
        pw.flush();
    }catch(Exception e){
        e.printStackTrace();
    }
}

public List<String> translate(String[] str){
    List<String> r = new ArrayList<String>();
    for (String s : str){
        r.add(s);
    }
    return r;
}

public String[] recieve(Socket s){
    String[] r = null;
    try{
        ArrayList<String> lines = new ArrayList<String>();
        InputStream is = s.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println("SRECIEVE >> "+line);
            lines.add(line);
        }
        r = new String[lines.size()];
        for (int i = 0; i < lines.size(); i++){
            r[i] = lines.get(i);
        }
    }catch(Exception e){
        e.printStackTrace();
    }
    return r;
}

public void sendToAll(String str){
    for (Socket soc : s){
        send(soc, str);
    }
}

我的問題很簡單,就是沒有消息被接收/發送。 當我啟動服務器時,它將啟動客戶端並完美連接,但是當我進入

try{
                s = new Socket(ip, port);
                System.out.println("CONNECTION >> Waiting for conformation with name "+name+"!");
                send("#reg"+name);
                WaitForMessage("#confirmed");
                System.out.println("CONNECTION >> You have been registered to server!");
                while (true){
                    List<String> recieve = recieve();
                    if (!recieve.isEmpty()){
                        for (String str : recieve){
                            System.out.println(str);
                        }
                    }
                }
            }catch(Exception e){
                e.printStackTrace();
            }

什么也沒有發生。

您正在閱讀台詞,但您沒有在寫台詞。 使用println()代替write() 並修復@PeterLawrey提到的所有問題。 如果readLine()返回null,則關閉套接字並停止讀取。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM