javaoop网络编程

1.网络 编程的本质就是说:

      服务器端(serverSocket)<===>客户端(socket)

     对于 有很多的 线程的 实现, 就是说 服务器端需要提供 多线程的 

                 既是 实现 Runnable 接口而已

其中 很重要的 就是 服务端 需要的是  先 接收 BufferReader ins 的实现

                                        ins.readLine();

++++++++++++++++++++++++++++++++++++++++++

 

这是 服务器端的 多线程 实现
public class MyThreadServer implements Runnable {

Socket socket=null;
//输出消息对象
PrintWriter out=null;
//输入消息对象
BufferedReader ins=null;

//构造方法的初始化 
public MyThreadServer(Socket socket){
this.socket=socket;
System.out.println("创建线程!");
try {
out=new PrintWriter(socket.getOutputStream(), true);
ins=new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}


public void run() {
while(true){
try {
System.out.println("开始接收消息。。。。。。");
//接收客户端发送过来 的消息


String msg = ins.readLine();

//显示接收到的消息
System.out.println("接收的消息为:"+msg);
if(msg.equals("exit")){
//如果客户端要退出
System.out.println("服务器端退出!!!");
break;
}

msg = JOptionPane.showInputDialog("请输入需要发送的消息:");
// 这是 服务端 把消息 发送给 客户端
out.println(msg);

} catch (IOException e) {
e.printStackTrace();
}
}

try{
if(ins!=null){
ins.close();
}
if(out!=null){
out.close();
}
if(socket!=null){
socket.close();
}
}catch(Exception e ){
e.printStackTrace();
}

}

}

++++++++++++++++++++++++++++++++++++++++

public class MyServerMain {

public static void main(String[] args) {
try{
//建立服务器端监听对象
ServerSocket server=new ServerSocket(8999);
while(true){
System.out.println("进入监听状态!");
//一直监听获取客户端的链接
Socket socket=server.accept();
MyThreadServer mythread=new MyThreadServer(socket);
new Thread(mythread).start();
}
}catch(Exception e){
e.printStackTrace();
}

}

}

++++++++++++++++++++++++++++++++++++

public class MyClient {

public static void main(String[] args) {
try {

System.out.println("已经建立连接。。。。。。");
Socket client=new Socket("127.0.0.1", 8999);

//输出消息对象
PrintWriter out=new PrintWriter(client.getOutputStream(), true);

//输入消息对象
BufferedReader ins=new BufferedReader(new InputStreamReader(client.getInputStream()));
//先输出给 服务端
out.println("服务器你好,我是客户端!");
//然后 在接收
String msg = ins.readLine();

//System.out.println("服务器端说:---->>>"+msg);
while(true){
//输入要发送的消息
msg = JOptionPane.showInputDialog("请输入发送给服务器的消息:");
out.println(msg);//将消息发送给服务器端

if(msg.equals("exit")){
System.out.println("客户端退出。。。");
break;
}

msg = ins.readLine();
JOptionPane.showMessageDialog(null, "服务器端说:---->>>"+msg);
}
ins.close();
out.close();
client.close();

} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

}

++++++++++++++++++++++++++++++++++++

原文地址:https://www.cnblogs.com/yyjxxd/p/5475278.html