Socket套接字
I/O流
inputsteam
outputsteam
read
writte
服务端;
1.建立serverSocket对象
2.等待客户端连接,返回一个Socket对象
3.建立与客户段的输入或输出流
4.关闭资源
try {
//1.建立服务端 对象
ServerSocket ss = new ServerSocket(8888);
//2.等待客户端链接
Socket s = ss.accept(); //阻塞式的方法
//建立服务端和客户端的输入和输出流
OutputStream out = s.getOutputStream();
String str = "你好fsdfasdfa";
//输出
out.write( str.getBytes());
s.close();
ss.close();
} catch (IOException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
}
客户端:
1.建立socket对象,参数:主机地址和端口
2.建立与服务段的输入或输出流
3.关闭资源
try {
Socket s = new Socket("localhost" ,8888);
InputStream in = s.getInputStream();
//字符流接受
byte[] b = new byte[1024];
int len ;
String str = null;
StringBuffer sb = new StringBuffer();// stringbuffer 解决字符串连接的常量池 内存
while((len = in .read(b ))!=-1){
str = new String(b ,0,len );
sb.append( str);
}
System. out.println(sb .toString());
s.close();
} catch (UnknownHostException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
}
posted on
浙公网安备 33010602011771号