我想从客户端传递一个对象到服务端 然后再通过服务端转发给另外一个客户端 请问如何来实现 给点思路啊 各位达人们!! 能给个小demo 最好
这是我写的一个小测试 但有问题不能达到效果 脑子有点笨 给个指点啊
============server ===========
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import javax.naming.ldap.StartTlsRequest;
public class Server {
private Socket socket;
private BufferedReader read;
private BufferedWriter writer;
private InetAddress address;
private int port;
public void receive(ServerSocket serversocket){
while(true){
try {
socket = serversocket.accept();
address = socket.getInetAddress();
port = socket.getPort();
new Thread(new Runnable(){
public void run() {
try {
StringBuffer Message = new StringBuffer();
read = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String temp = read.readLine();
while(temp!=null){
Message.append(temp);
temp = read.readLine();
}
send(Message,socket);
System.out.println("===Server receive==="+Message+
"=== IP ==="+address+"===Port==="+port);
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
read.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
private boolean send(StringBuffer Message,Socket sendSocket){
System.out.println("===== Send Message ====="+Message);
try {
writer = new BufferedWriter(new OutputStreamWriter(sendSocket.getOutputStream()));
writer.write(new String(Message));
} catch (IOException e) {
e.printStackTrace();
try {
writer.close();
sendSocket.close();
} catch (IOException e1) {
e1.printStackTrace();
return false;
}
return false;
}
return true;
}
}
===============clinet==============
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
Socket socket;
BufferedWriter out;
BufferedReader in;
public boolean send(String str){
try {
socket = new Socket("localhost",8888);
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
out.write(str);
out.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
public StringBuffer receive(ServerSocket ssocket){
String temp=null;
StringBuffer Message = new StringBuffer();
try {
socket = ssocket.accept();
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
temp = in.readLine();
while(temp!=null){
Message.append(temp);
temp = in.readLine();
}
in.close();
System.out.println("===== Clinte Message ====="+Message);
} catch (IOException e) {
e.printStackTrace();
}
return Message;
}
}