论坛首页 Java企业应用论坛

java网络编程:socket与sockeserver

浏览 5255 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (1) :: 隐藏帖 (0)
作者 正文
   发表时间:2013-04-21  

今晚上开始研究java的网络编程,先从socket开始吧。下面是一个简单的client/server的例子:

客户端代码:

public class TCPECHOClient {
	public static void main(String[] args) {
		String server = "localhost";
		String data = "Echo this!";
		byte[] bs = data.getBytes();
		try {
			Socket socket = new Socket(server,80);
			System.out.println("Connecting to server……");
			InputStream in = socket.getInputStream();
			OutputStream out = socket.getOutputStream();
			out.write(bs);
			int totalDateRecived = 0;
			int bytesRecvd = 0 ;
			while(totalDateRecived<bs.length){
				totalDateRecived +=bytesRecvd;
				if((bytesRecvd=in.read(bs,totalDateRecived,bs.length-totalDateRecived))==-1)
				throw new SocketException("connection closed!");
			}
			System.out.println("received:"+new String(bs));
			socket.close();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

 服务端:

public class TCPEchoServer {
	private static int BUFSiZE = 32;
	public static void main(String[] args) {
		try {
			ServerSocket serverSocket = new ServerSocket(80);
			int received = 0;
			byte[] receiveBuf =  new byte[BUFSiZE];
			while(true){
				Socket socket = serverSocket.accept();
				SocketAddress clientAddress = socket.getRemoteSocketAddress();
				System.out.println("handling client at:"+clientAddress);
				InputStream in = socket.getInputStream();
				OutputStream out = socket.getOutputStream();
				while((received=in.read(receiveBuf))!=-1){
					out.write(receiveBuf,0,received);
				}
				socket.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

 输出结果:

客户端:Connecting to server……
received:Echo this!

服务端:handling client at:/127.0.0.1:50884

   发表时间:2013-04-26  
你这个代码  没有使用线层  多个客户端 怎么办。每次只能处理一个请求。
0 请登录后投票
   发表时间:2013-04-27  
lohasle 写道
你这个代码  没有使用线层  多个客户端 怎么办。每次只能处理一个请求。

这个只是最简单的例子,对应TCP我也是初学者。
0 请登录后投票
   发表时间:2013-04-28  
其实这样的代码基本上大家都能写,可是,谁又能了解每一行代码操作系统的底层都在干什么呢?
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics