Tcp实现客户端和服务器端的简单互访

import java.io.*;
import java.net.*;
public class TCPServer1 {
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		ServerSocket ss=new ServerSocket(10005);
		Socket s=ss.accept();
		
		InputStream is=s.getInputStream();
		
		byte[] b=new byte[1024];
		int len=is.read(b);
		if(len!=0){
			System.out.println(new String(b,0,len));
		}	
		OutputStream os=s.getOutputStream();
		os.write("ni ye hao".getBytes());
		
		s.close();
		ss.close();
	}
}

import java.io.*;
import java.net.*;
import java.util.Arrays;
public class TCPClient1 {
	public static void main(String[] args) throws UnknownHostException, IOException {
		// TODO Auto-generated method stub
		Socket s=new Socket("127.0.0.1",10005);
		
		OutputStream os=s.getOutputStream();
		os.write("nihao".getBytes());
		
		InputStream is=s.getInputStream();
		byte[] b=new byte[is.available()];
		is.read(b);
		System.out.println(new String(b));//ni ye hao
		System.out.println(Arrays.toString(b));//	[110, 105, 32, 121, 101, 32, 104, 97, 111]如果不用这个方法的话打印出来的将会是地址值
	}

}

你可能感兴趣的:(java)