java 网络编程 摘记1

Java中接受其他通信实体连接请求的类是ServerSocket。该对象用于监听来自客户端的Socket连接,如没连接,一直处于等待状态。

客户端使用用Socket来的构造器来连接指定服务器。

以下是两端的code示例:

public class Client
{
	public static void main(String[] args) throws IOException
	{
		Socket s = new Socket(“127.0.0.1”,30000);
		BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputSteam()));
		System.out.println("come from server:" + br.readLine());
		br.close();
		socket.close();
	}
}

public class Server
{
	public static void main(String[] args) throws IOException
	{
		Socket ss = new ServerSocket(30000);
		while(true)
		{
			Socket s = ss.accept();
			PrintStream ps = new PrintStream(s.getOutputStream());
			ps.println("welcome to receive msg from server")
		}
		ps.close();
		s.close();
	}
}
多线程:下面实现一个客户端(一个Socket对应一个线程,一个客户端)将读取的信息广播到其他客户端。
public class  MyServer
{
	//save all ArrayList of Socket
	public static ArrayList<Socket> socketList = new ArrayList<Socket>();
	public static void mian(String[] args) throws IOException
	{
		ServerSocket ss =new ServerSocket(30000);
		while(true)
		{
			//waiting for others'link
			Socket s = ss.accept();
			sockeList.add(s);
			//when client link ,then star a ServerThread for it
			new Thread(new ServerThread(s)).start();
		}
	}
}

public class ServerThread implements Runnable
{
	//define current thread processed Socket
	Socket s = null;
	//IO with this thread
	BufferedReader br =null;
	public ServerThread(Socket s)throws IOException
	{
		this.s=s;
		//int Socket IO
		br= new BufferedReader(new InpuStreamReader(s.getInputStream()));
	}
	public void run()
	{
		try
		{
			String content = null;
			while((content = readFromClient())!=null)
			{
				for(Socket s:MyServer.socketList)
				{
					PrintStream ps = new PrintStream(s.getOutputStream());
					ps.println(content);
				}
			}
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
	private String readFromClient()
	{
		try
		{
			return br.readLine();
		}
		catch (IOException e)
		{
			MyServer.socketList.remove(s);
		}
	return null;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值