java基础学习笔记——网络TCP/Client&Server

</pre><pre name="code" class="java">package ownerSocket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerDemo {

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		System.out.println("Server start.....");
		
		ServerSocket ss = new ServerSocket(10004);
		Socket s = ss.accept();
		
		byte[] b = new byte[1024];
		InputStream in = s.getInputStream();
		int len = in.read(b);
		String str = new String(b,0,len);
		System.out.println("服务端收到:"+str);
		
		OutputStream out = s.getOutputStream();
		out.write("服务端收到".getBytes());
		
		ss.close();
		s.close();

	}

}

package ownerSocket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class ClientDemo {

	/**
	 * @param args
	 * @throws IOException 
	 * @throws UnknownHostException 
	 */
	public static void main(String[] args) throws UnknownHostException, IOException {
		// TODO Auto-generated method stub
		System.out.println("Client start....");
		Socket socket = new Socket(InetAddress.getByName("lenovo-PC"), 10004);
		
		OutputStream out = socket.getOutputStream();
		
		out.write("客户端发出消息....".getBytes());
		
		InputStream in = socket.getInputStream();
		byte[] b = new byte[1024];
		int len = in.read(b);
		String str = new String(b,0,len);
		System.out.println("客户端收到服务端内容:"+str);
		
		socket.close();
		
	}

}


你可能感兴趣的:(java基础学习笔记——网络TCP/Client&Server)