我正在尝试创建一个messenger程序,并使用套接字成功设置了客户端 - 服务器连接。但是我发现很难对几个客户端同时进行通信的过程进行编码。下面的代码中显示了ClientThread类中保存的聊天的方法,该类使用存储在共享ArrayList中的线程来调节客户端和服务器之间的交互。您将如何在此处实现多个点对点聊天的代码?
startChat方法:
public void startChat()
{
// start the convo!
// first of all the user chooses who to speak to
// starts a loop until user enters a valid username or 'Group'
String line = "";
boolean validCommand = false;
while(validCommand == false)
{
try {
line = in.readLine();
} catch (IOException e) {
System.out.println("Problem reading reply about user chat");
}
if(line.equalsIgnoreCase("Group"))
{
validCommand = true;
chatAll(); // an integer of negative one starts a chat with everyone
}
else
{
synchronized(this){
// find user
for(int i = 0; i < threads.size(); i++)
{
if(threads.get(i) != null && threads.get(i).username != null)
{
if(threads.get(i).username.equals(line)) // means that we have found the index of the thread that the client wants to speak to
{
/*// START : BETWEEN THESE CAPITALISED COMMENTS IS MY ATTEMPT TO INITIATE TWO WAY CHAT
int thisIndex = -1;
for(int j = 0; j < threads.size(); j++) // gets the index of this thread object in the array
{
if(threads.get(j) == this)
{
thisIndex = j;
// out.println(j);
}
}
if(thisIndex != -1)
{
threads.get(i).out.println(username + " is trying to connect");
threads.get(i).processChat(thisIndex); // this is the line causing the problem!
}
// END : BETWEEN THESE CAPITALISED COMMENTS IS MY ATTEMPT TO INITIATE TWO WAY CHAT */
threads.get(i).out.println(username + " is trying to connect");
out.println("Chat with " + threads.get(i).username);
processChat(i);
validCommand = true;
}
// if the command is not group and not a username, it is not valid and we ask the user to re-enter
else if(i == threads.size() - 1)
{
out.println("This command is not valid, please re-enter");
}
}
}
} // end of synchronised bit
} // end of else statement
} // end of while loop
}
allChat方法:
void chatAll()
//for the purpose of group chat
{
out.println("Group chat initiated");
boolean d = true;
while(d == true)
{
String message = "";
try {
message = in.readLine();
} catch (IOException e) {
System.out.println("Can't read line from client");
}
if(message.contains("goodbye") == true)
{
d = false;
}
else
{
synchronized(this)
{
for(int j = 0; j < threads.size(); j++)
{
if(threads.get(j) != null)
{
threads.get(j).out.println(username + ": " + message);
}
}
}
}
}
}
processChat方法:
void processChat(int i)
//for the purpose of talking to pre-defined user
{
boolean d = true;
while(d == true)
{
String message = "";
try {
message = in.readLine();
} catch (IOException e) {
System.out.println("Can't read message from client");
}
if(message.contains("goodbye") == true)
{
d = false;
}
else {
if(threads.get(i) != null)
{
threads.get(i).out.println(username + ": " + message);
}
}
}
}
只是为了好的衡量,这里的引用是整个客户端类(混淆标记为ThreadedClient而不是ClientThread哈哈)
ThreadedClient类:
import java.net.*;
import java.io.*;
public class ThreadedClient implements Runnable {
// client socket
private static Socket clientSocket = null;
//I/O streams to and from the server
private static BufferedReader in = null;
private static PrintStream out = null;
// Input stream to read user input
private static BufferedReader inputReader = null;
private boolean open = true;
public ThreadedClient(String host, int port)
{
startConnection(host, port);
}
public void startConnection(String host, int port)
{
//open up the socket
try {
clientSocket = new Socket(host, port);
} catch (UnknownHostException e) {
System.out.println("The host name '" + host + "' isn't known");
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Cannot create socket");
}
// connect I/O streams
try {
in = new BufferedReader(new InputStreamReader(new DataInputStream(clientSocket.getInputStream())));
out = new PrintStream(clientSocket.getOutputStream());
inputReader = new BufferedReader(new InputStreamReader(System.in));
} catch (IOException e) {
System.out.println("Problem connecting streams");
}
// process the chat itself
// the thread deals with input coming in
Thread thread = new Thread(this);
thread.start();
// the loop deals with output
while(open == true)
{
String message;
try {
message = inputReader.readLine();
out.println(message);
if(message.contains("goodbye") == true)
{
open = false;
}
} catch (IOException e) {
System.out.println("Problem sending messages");
}
}
// chat is done, so we can close resources
try {
in.close();
inputReader.close();
out.close();
clientSocket.close();
} catch (IOException e) {
System.out.println("Problem closing resources");
}
}
// run method for sending input out. I imagine this will not be necessary in the GUI implemented version, as we can use
// an action listener for the send function, e.g. one that reads a text field into a output stream everytime the user clicks enter
public void run() {
while(open == true)
{
try {
String response = in.readLine();
if(response.contains("goodbye") == true)
{
open = false;
}
System.out.println(response);
} catch (IOException e) {
System.out.println("Problem recieving messages");
}
}
}
public static void main(String[] args)
{
ThreadedClient socket = new ThreadedClient("localhost", 50000);
}
}
我知道这段代码可能不像我在这个论坛以及DreamInCode和其他人看到过的其他代码那么先进,但我试图从头开始构建它并且已经被困在这里,感觉就像几千年一样。在互联网上拖网没有帮助:(
任何建议和批评都是绝对的神派!
先谢谢你们。
答案 0 :(得分:0)
我可以给你一个解决方案,但你必须实现它
我们有:
- 服务器A,客户B&amp; C. B&amp; C已经通过TCP连接连接到服务器
- 第一个,客户端B想要与C聊天。所以B必须通过UDP向服务器发送消息
- 2,服务器将收到来自B ==&gt;的UDP消息。服务器知道哪个ip&amp; B的端口,B通过UDP连接到服务器。然后,服务器向C发送一条消息(TCP),其中包含有关UDP ip:B端口的信息
- 第三:客户端C将通过TCP从服务器接收该消息。所以C知道ip:B正在听的端口.--&gt;如果C接受与B聊天。 C必须向服务器发送UDP消息,告诉服务器C接受与B通话
- 4th:服务器将通过UDP接收该消息。所以Server也知道ip:UDP中的C端口
- 5:服务器将通过TCP(或UDP,如果需要)将UDP ip:C端口传输到B.
- 第6次:客户B将收到它&amp;知道udp ip:C的端口。所以他们现在可以开始通过UDP协议聊天了。
IT称为UDP / TCP打孔。您可以对其进行更多研究以实施。
P / S:但这种方法不适用于Symetric NAT
答案 1 :(得分:0)
行。
你可以这样做:我专注于控制台应用程序
- 定义课堂电话留言:
class Message
{
public String username; // the sender that send this message to u.So you can reply back to this user
public boolean groupMessage; // this message is group message or not
public String message;
}
因此,当您开始与客户聊天时 - &gt;创建新线程以从他那里读取消息。当您收到消息时。您必须将该消息放入数组列表:消息(您必须记住同步它。因为它将被许多线程调用)
synchorized(消息){ messages.add(....); //这里有新消息 }
然后,您创建一个新的线程来显示消息&amp;可以回复发件人。在此阅读中,您将从数组列表消息&amp;中弹出一条消息。展示下。
而(isrunning) {
synchorized(messages){
if(messages.size()<=0) messages.wait(); // when you receive a new message you have to notify
}
synchorized(messages){
Message msg = messages.get(0);
messages.remove(0);
showmessage_to_ouput(msg); // something like this.
String s = read from input // to reply to this message.
Reply(....)// here you can check if this message is group message--> reply to all,..etc
}
}