socket是网络编程的基础,虽然说现在的开发中很多都是有已经封装好的socket通信框架,但是学习socket还是很有必要的
socket客户端
public class MinaClient {
public static void main(String args[]){
MinaClient minaClient=new MinaClient();
minaClient.start();
}
public void start(){
//第一步,创建socket对象
Socket socket=null;
//第二步,创建流
OutputStreamWriter outputStreamWriter=null;
BufferedWriter writer=null;
BufferedReader reader=null;
try {
socket=new Socket("127.0.0.1",9988);
outputStreamWriter = new OutputStreamWriter(socket.getOutputStream());
writer = new BufferedWriter(outputStreamWriter);
reader = new BufferedReader(new InputStreamReader(System.in));
String msg;
//第三步,读写流
while(!(msg=reader.readLine()).equals("\n")){
writer.write(msg+"\n");
writer.flush();//注意flush是清空缓存中的数据,如果没有调用这个方法就关闭writer会导致数据丢失
System.out.println(msg);
}
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
finally{
try {
//第四步,关闭socket和流
socket.close();
reader.close();
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
socket服务器端
public class MinaServer {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("main");
MinaServer server=new MinaServer();
server.startServer();
}
public void startServer(){
//第一步,创建socketserver对象
ServerSocket serverSocket = null;
//第二步,创建流对象
BufferedReader reader = null;
try {
serverSocket=new ServerSocket(9988);
//第三步,等待客户端接入
Socket socket=serverSocket.accept();
reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
String lineString;
//第四步,读写
while((lineString=reader.readLine())!=null){
System.out.println("client"+socket.hashCode()+":"+lineString);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
//第五步,关闭socket和流
serverSocket.close();
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}