用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - java代码库

网络编程的一些基本原理

2013-10-06 作者: he举报

[java]代码库

package com.qq.MyClient;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

import com.qq.user.SendToMessage;
import com.qq.user.user;

public class MyServer {
	ServerSocket server;
	public MyServer() {
		try {
			server=new ServerSocket(8000);
			while(true){
				System.out.println("服务器正在监听....");
				Socket socket=server.accept();
				ObjectInputStream ois=new ObjectInputStream(socket.getInputStream());
				user u=(user)ois.readObject();
				
				ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream());
				SendToMessage sm=new SendToMessage();
				//判断密码
				if("123456".equals(u.getUserPd())){
					sm.setMessType("1");
					oos.writeObject(sm);
					sendMessageToClient smt=new sendMessageToClient(socket);
//					Thread t=new Thread(smt);
					
					magaeMessage.addSendMessage(u.getUserId(),smt);
					smt.start();
					
					
					
					
				}else{
					sm.setMessType("2");
					oos.writeObject(sm);
				}
				
				
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
//	public static void main(String[] args) {
//		new MyServer();
//	}
}
class sendMessageToClient extends Thread{
	Socket socket;
	public sendMessageToClient(Socket socket) {
		this.socket=socket;
	}
	@Override
	public void run() {
		SendToMessage sm;
		while(true){
			try {
				ObjectInputStream ois=new ObjectInputStream(socket.getInputStream());
				sm=(SendToMessage)ois.readObject();
				
				sendMessageToClient st=magaeMessage.checksendMessageToClient(sm.getGetter());
				ObjectOutputStream  oos=new ObjectOutputStream(st.socket.getOutputStream());
				oos.writeObject(sm);
				System.out.println();
				System.out.println(sm.getSender()+"给"+sm.getGetter()+"说:"+sm.getMessage());
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	}
	
}
class magaeMessage{
	public static Map<String, sendMessageToClient> hm =new HashMap<String,sendMessageToClient>();
	public static void addSendMessage(String id,sendMessageToClient mc){
		hm.put(id, mc);
	}
	public static sendMessageToClient checksendMessageToClient(String id){
		return (sendMessageToClient)hm.get(id);
	}
}





网友评论    (发表评论)

共2 条评论 1/1页

发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...