客户端是不是这么接收服务器端的消息的
package test;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Scanner;
public class ClinetSocket extends Thread {
private Socket socket;
public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException{
new ClinetSocket().login();
}
public void login() throws UnknownHostException, IOException, ClassNotFoundException{
Scanner sc=new Scanner(System.in);
System.out.print("请输入您的昵称:");
User u= new User(sc.nextLine());
Socket socket=new Socket("127.0.0.1", 10);
OutputStream output= socket.getOutputStream();
ObjectOutputStream objout=new ObjectOutputStream(output);
objout.writeObject(u);
this.socket=socket;
this.start();
/*while(true){
InputStream input= socket.getInputStream();
ObjectInputStream objInput=new ObjectInputStream(input);
List list= (List)objInput.readObject();
if(list!==null&&!list.isEmpty()){
System.out.println("当前在线用户:");
for(int i=0;i<list.size();i++){
}
}
}*/
while(true){
System.out.print("您说:");
String mesg= sc.nextLine();
output.write(mesg.getBytes());
}
}
public void run(){
InputStream input=null;
try {
input= this.socket.getInputStream();
while(true){
byte[] b=new byte[input.available()];
input.read(b);
if(b.length>0){
System.out.println("\n"+new String(b));
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class User implements Serializable{
private String name;
public User(String name){
this.name=name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
这是客户端代码,我使用了一个线程去无线等待接受服务器消息,不知道实际的应用中是不是这么使用线程来接受服务器端发送的消息