java服务端客户端代码 java服务端客户端代码是多少( 三 )


if(messageline.getType().equals("USER")){
setupUserName(messageline.getBody());
parent.broadcastMessage("LIST:"+parent.returnUsernameList());
}
else if(messageline.getType().equals("MESSAGE")){
parent.broadcastMessage("MESSAGE:"+user+"说: "+messageline.getBody());
}
else if(messageline.getType().equals("LEAVE")){
String c=disconnectClient();
parent.broadcastMessage("REMOVE:"+c);
parent.broadcastMessage("LIST:"+parent.returnUsernameList());
}
}
else
sendMessage("命令不存在!");
}
public String disconnectClient(){
try{
in.close();
out.close();
theSocket.close();
parent.removeConnectionList(this);
disconnect=true;
}catch(Exception ex){}
return user;
}
public void run(){
String line,name;
boolean valid=false;
try{
while((line=in.readLine())!=null){
System.out.println("收到:"+line);
extractMessage(line);
}
}catch(IOException io){}
}
}
=========================================================
Message.javapublic class Message{
private String type;
private String body;
private boolean valid;
public Message(String messageLine){
valid=false;
type=body=null;
int pos=messageLine.indexOf(":");
if(pos=0){
type=messageLine.substring(0,pos).toUpperCase();
body=messageLine.substring(pos+1);
valid=true;
}
}
public Message(String type,String body){
valid=true;
this.type=type;
this.body=body;
}
public String getType(){
return type;
}
public String getBody(){
return body;
}
public boolean isValid(){
return valid;
}
} ==================================================共有4个文件 , 先运行服务段端 。。。这是我以前学的时候写过的!希望能帮的上你
编写java程序实现客户端和服务端的通信服务器端:
public class Server{
public static void main(String[] args){
ServerSocket ss = new ServerSocket(端口号);
Socket s = ss.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String str = br.readLine();
System.out.println(str);
br.close();
s.close();
ss.close();
}
}
客户端:
public class Client{
public static void main(String[] args){
Socket s = new Socket(ip,端口)
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
bw.write("hello");
bw.flush();
bw.close();
s.close();
}
}
先启动服务器端在启动客户端,两个端口要一致 , 如果是同一台电脑的ip可写为"127.0.0.1"
java socket , 我有客户端和服务器的代码,帮我添加广播和能多人会话,加分?。〈肴缦?/h2>根据你的改了个!不好意思,其中读写的思路稍微有点不同!不过可以做参考!
Server端代码:
import java.net.*;
import java.io.*;
import java.util.*;
public class TestServer {
ServerSocket s = null;
boolean started = false;//用来监听服务器是否启动!
ListServerReaderWriter clients = new ArrayListServerReaderWriter();//用来存放启动的客服端
public static void main(String[] args) {
new TestServer().start();
}
public void start() {
try {
s = new ServerSocket(5050);
started = true;
} catch(SocketException e) {
System.out.println("5050端口正在使用中?。。∏牍氐粝喙爻绦虿⒅匦略诵蟹衿鳎?);
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
int i = 1;
try {
while(started) {
Socket ss = s.accept();

推荐阅读