我正在根据我发现的一个简单教程制作一个 TCP 聊天服务器,我是 java 的新手。我最终会创建一个客户端类,但到目前为止我一直在通过 telnet 对其进行测试。我有几个问题。我已将服务器设置为从客户端获取命令。例如,关闭客户端连接的“EXIT”和打印“OK”的“Username”。如下图:
用户 1:TIM
Welcome to Bob's Chat Server!
Please Enter a User Name:
Tim
Welcome Tim we hope you enjoy your chat today
Bob:Hello
Hi Bob
Tim
OK
EXIT
Closing Connection . . . Goodbye
用户 2:鲍勃
Welcome to Bob's Chat Server!
Please Enter a User Name:
Bob
Welcome Bob we hope you enjoy your chat today
Hello
Tim:Hi Bob
Tim:Tim
我想解决三个问题:
你会注意到,当用户 1 键入“Tim”(他的用户名)时,它像我想要的那样说“OK”,但它也向用户 2 打印了“Tim”。有没有办法让它不发送我输入的命令?因此,当我键入“Tim”时,它不会向 USER 2 打印“Tim”吗?
当消息被发送给其他用户时,它会显示是谁说的。有没有办法在两个连接上打印名称?例如,当用户 2 说“你好”时,它在两个连接上看起来更像是“鲍勃:你好”?
有没有办法跟踪整个聊天 session 中所说的所有内容,并将聊天的全部内容打印到任何用户请求的地方?
这是我的服务器代码:
// Chat Server runs at port no. 9020
import java.io.*;
import java.util.*;
import java.net.*;
import static java.lang.System.out;
public class TCPServer
{
Vector<String> users = new Vector<String>();
Vector<HandleClient> clients = new Vector<HandleClient>();
int PORT = 9020;
int NumClients = 10;
public void process() throws Exception
{
ServerSocket server = new ServerSocket(PORT,NumClients);
out.println("Server Connected...");
while( true)
{
Socket client = server.accept();
HandleClient c = new HandleClient(client);
clients.add(c);
} // end of while
}
public static void main(String ... args) throws Exception
{
new TCPServer().process();
} // end of main
public void boradcast(String user, String message)
{
// send message to all connected users
for (HandleClient c : clients)
if (!c.getUserName().equals(user))
{
c.sendMessage(user,message);
}
}
class HandleClient extends Thread
{
String name = "";
BufferedReader input;
PrintWriter output;
public HandleClient(Socket client) throws Exception
{
// get input and output streams
input = new BufferedReader(new InputStreamReader(client.getInputStream())) ;
output = new PrintWriter (client.getOutputStream(),true);
output.println("Welcome to Bob's Chat Server!\n");
// read name
output.println("Please Enter a User Name: ");
name = input.readLine();
users.add(name); // add to vector
output.println("Welcome "+name+" we hope you enjoy your chat today");
start();
}
public void sendMessage(String uname,String msg)
{
output.println( uname + ":" + msg);
}
public String getUserName()
{
return name;
}
public void run()
{
String line;
try
{
while(true)
{
line = input.readLine();
if("EXIT".equals(line))
{
output.println("Closing Connection . . . Goodbye");
clients.remove(this);
users.remove(name);
break;
}
else if(name.equals(line))
{
output.println("OK");
}
boradcast(name,line); // method of outer class - send messages to all
}// end of while
} // try
catch(Exception e)
{
System.out.println(e.getMessage());
}
} // end of run()
} // end of inner class
} // end of Server
感谢任何帮助。谢谢。
最佳答案
我已经根据您的喜好修改了您的代码,请看一下:
对于第 1 点:
public void run()
{
String line;
try
{
while(true)
{
line = input.readLine();
if("EXIT".equals(line))
{
output.println("Closing Connection . . . Goodbye");
clients.remove(this);
users.remove(name);
break;
}
else if(name.equals(line))
{
output.println("OK");
}
else
{
// Seems to me just adding this else part will do the trick for point one.
boradcast(name,line); // method of outer class - send messages to all
}
}// end of while
} // try
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
对于第 2 点:
在我看来,您正在向控制台输入内容以获取输入,在这种情况下,至少有一次您必须输入必须发送给另一端的内容,然后您可以添加修改,如下所示方法的第一行,broadcast();,这样你就可以满足你对Point 2的需求,或者(else你可以让服务器端将它发送回客户端,包含名称的消息,它就像客户端将消息发送到服务器,服务器将所有客户端发回。)
public void boradcast(String user, String message)
{
System.out.println(user + " : " + message);
// send message to all connected users
for (HandleClient c : clients)
if (!c.getUserName().equals(user))
{
c.sendMessage(user,message);
}
}
对于第 3 点,您可以将对话写入文件或将其保存到数据库,无论哪种方式都适合您。
既然你说你是 Java 的新手,你最好看看 java.nio .这个包比之前的 java.io 包要好。
最新编辑:
试试这个小示例代码,希望它能满足您的要求:
import java.io.*;
public class StringConsole
{
public static void main(String... args) throws IOException
{
int count = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (count < 5)
{
System.out.print("My Name : ");
String message = br.readLine();
count++;
}
}
}
希望这能以某种方式帮助您。
问候
关于java - 简单的 Java 聊天服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9058767/