码迷,mamicode.com
首页 > 其他好文 > 详细

服务端和客户端互聊

时间:2018-12-29 13:37:51      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:output   java.net   val   todo   lin   put   stream   int   string   

package socket;
 
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
 
public class Server {
 
    public static void main(String[] args) {
        try {
 
            ServerSocket ss = new ServerSocket(8888);
 
            System.out.println("监听在端口号:8888");
            Socket s = ss.accept();
 
            InputStream is = s.getInputStream();
            DataInputStream dis = new DataInputStream(is);
            OutputStream os = s.getOutputStream();
            DataOutputStream dos = new DataOutputStream(os);
 
            while (true) {
                String msg = dis.readUTF();
                System.out.println("收到客户端信息"+msg);
                Scanner sc = new Scanner(System.in);
                String str = sc.next();
                dos.writeUTF(str);
            }
 
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
 
    }
}
 
 
 
 
 
 
 
package socket;
  
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
  
public class Client {
  
    public static void main(String[] args) {
  
        try {
            Socket s = new Socket("127.0.0.1"8888);
  
            OutputStream os = s.getOutputStream();
            DataOutputStream dos = new DataOutputStream(os);
            InputStream is = s.getInputStream();
            DataInputStream dis = new DataInputStream(is);
              
            while(true){
                Scanner sc = new Scanner(System.in);
                String str = sc.next();
                dos.writeUTF(str);
                String msg = dis.readUTF();
                System.out.println("收到服务端信息"+msg);
            }
              
        catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

服务端和客户端互聊

标签:output   java.net   val   todo   lin   put   stream   int   string   

原文地址:https://www.cnblogs.com/chinaifae/p/10194916.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!