TCP

TCP_第1张图片

import java.net.*;
import java.io.*;

class Client 
{
	public static void main(String[] args) throws Exception
	{

		//1,建立客户端socket服务。
		Socket s = new Socket("192.168.1.254",10002);

		//2,获取socket中的输出流。
		OutputStream out = s.getOutputStream();

		out.write("tcp ge men you lai le ".getBytes());


		InputStream in = s.getInputStream();

		byte[] buf = new byte[1024];
		int len = in.read(buf);

		System.out.println(new String(buf,0,len));

		s.close();
	}
}


class  Server
{
	public static void main(String[] args) throws Exception
	{
		//1,建立服务端socket对象,必须要监听一个端口。

		ServerSocket ss = new ServerSocket(10002);

		//2.通过socket服务获取客户端对象通过accept方法。
		Socket s = ss.accept();

		String ip = s.getInetAddress().getHostAddress();
		System.out.println(ip+"....connect");

		//3,通过获取的客户端对象,获取读取流读客户端发来的数据。
		InputStream in = s.getInputStream();

		byte[] buf = new byte[1024];

		int len = in.read(buf);

		System.out.println(new String(buf,0,len));

		OutputStream out = s.getOutputStream();

		out.write("shou dao !".getBytes());


		s.close();
		ss.close();
	}
}

 

你可能感兴趣的:(tcp)