我需要进行客户端-服务器-客户端消息传输。现在,我有一台服务器用新线程连接客户端。只需要执行邮件传输,我该怎么做?
我有一个服务器部件(在单独的包装中)
class WebServerHandler {
static int clientsCount = 0;
static ThreadGroup clientList;
WebServerHandler(){
}
public static void main(String...args)throws IOException
{
ServerSocket serverSocket = new ServerSocket(80, 10000,InetAddress.getByName("localhost"));
System.out.println("Server Started !");
while(true){
Socket defaultSocket = serverSocket.accept();
Thread client = new Thread(clientList,new WebServer(defaultSocket),"Client"+clientsCount);
client.start();
System.out.println("Connected a new client, now: " + clientsCount);
}
}
}
class WebServer implements Runnable
{
private Socket userSocket;
WebServer(Socket socket){
userSocket = socket;
WebServerHandler.clientsCount++;
}
public void run(){
try {
BufferedReader in;
/* socket = serverSocket.accept();
System.out.println("Connection Accepted : " + socket);*/
in = new BufferedReader(new InputStreamReader(userSocket.getInputStream()));/*
out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);*/
//DataInputStream inputStream = new DataInputStream(userSocket.getInputStream());
DataOutputStream outputStream = new DataOutputStream(userSocket.getOutputStream());
outputStream.writeUTF("Connected successfully! " + userSocket);
String str;
do {
str = in.readLine();
System.out.println("Echo from " + userSocket + " : " + str);
} while (!str.equals("stop"));
} catch (IOException e) { e.printStackTrace();}
finally {
try {
userSocket.close();
}
catch (IOException e){
e.printStackTrace();
}
}
}
}
和客户部件(在单独的包装中)
class TCPClient
{
public static void main(String...st)
{
Socket socket=null;
try {
try {
InetAddress address=InetAddress.getByName("localhost"); //returns 127.0.0.1 (I hope)
socket = new Socket(address,80);
System.out.println("Client Connected to Server = "+ socket);
//BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out=new PrintWriter(socket.getOutputStream(),true);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Start Typing :");
String str;
boolean flag=true;
while(flag)
{
str=br.readLine();
if(!str.equalsIgnoreCase("END")) {
out.println(str);
}
else {
flag=false;
out.println("END");
}
}
} catch(IOException e) { e.printStackTrace(); }
finally {
System.out.println("Closing Client Socket.....");
if(socket!=null)
socket.close();
}
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}
}
我正在使用多个客户端实例
我希望收到从客户端第一个实例发送到客户端第二个实例的消息。