服务器端和客户端
客户端发消息给服务器端,服务器端接收到数据,将其数据显示在控制台上。
服务器端代码:
//服务端
@Test
public void Server(){
ServerSocket ss= null;
Socket socket= null;
InputStream is= null;
ByteArrayOutputStream baos= null;
try {
//创建服务器端的ServerSocket,指明自己的端口号
ss = new ServerSocket(6565);
//调用accept(),表示接受来自于客户端的Socket
socket = ss.accept();
//获取输入流
is = socket.getInputStream();
// 不建议这么写,可能会乱码
// byte[] bytes=new byte[1024];
// int len;
// while((len=is.read(bytes))!=-1){
// String str=new String(bytes,0,len);
// System.out.print(str);
// }
//读取输入流中的数据
baos = new ByteArrayOutputStream();
byte[] buffer=new byte[5];
int len;
while((len=is.read(buffer))!=-1){
baos.write(buffer,0,len);
}
System.out.println(baos.toString());
System.out.println(socket.getInetAddress());
} catch (IOException e) {
e.printStackTrace();
} finally {
if(socket!=null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(ss!=null){
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(baos!=null){
try {
baos.close();
} catch (IOException e) {
}
}
}
}
客户端代码:
//客户端
@Test
public void client() {
Socket socket= null;
OutputStream os= null;
try {
//创建Socket对象,指明服务器端的端口号和ip
InetAddress inet=InetAddress.getByName("127.0.0.1");
socket = new Socket(inet,6565);
//获取输出流,用于获取数据
os = socket.getOutputStream();
os.write("你好".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭资源
if(os!=null)
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
if(socket!=null)
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
1,服务器端创建ServerSocket,设置端口号
2,用Socket来接收客户端的连接
3,客户端必须要知道连接服务器端的ip及端口号
4,站在服务器端的角度,客户端的流是输出流;服务端的流是输入流。