其他分享
首页 > 其他分享> > 屌丝与女神聊天,已读不回~socket简单小案例

屌丝与女神聊天,已读不回~socket简单小案例

作者:互联网

屌丝与女神聊天,已读不回~socket简单小案例

代码:

屌丝代码(客户端Socket)

package TCPDemo;


import java.io.IOException;
import java.io.OutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Scanner;



/**
 * 客户端Socket
 * @author Huangyujun
 *
 */
public class TCPSocket {
    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        Socket socket = new Socket("localhost", 9527);    //连接服务端
        //输出流、输入流
        OutputStream outStream = socket.getOutputStream();
        InputStream inStream =  socket.getInputStream();
        while(true) {
//            OutputStream outStream = socket.getOutputStream();
            System.out.println("屌丝发送消息:");
            String content  = scanner.next();
            content += "\n";
            //发送消息
            outStream.write(content.getBytes());
            if("退出".equals(content)) {
                break;
            }
            outStream.flush();
        }
    
        
    }
}

女神代码(服务端ServerSocket)

package TCPDemo;


import java.io.IOException;
import java.io.OutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Scanner;



/**
 * 客户端Socket
 * @author Huangyujun
 *
 */
public class TCPSocket {
    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        Socket socket = new Socket("localhost", 9527);    //连接服务端
        //输出流、输入流
        OutputStream outStream = socket.getOutputStream();
        InputStream inStream =  socket.getInputStream();
        while(true) {
//            OutputStream outStream = socket.getOutputStream();
            System.out.println("屌丝发送消息:");
            String content  = scanner.next();
            content += "\n";
            //发送消息
            outStream.write(content.getBytes());
            if("退出".equals(content)) {
                break;
            }
            outStream.flush();
        }
    
        
    }
}

 

标签:java,socket,已读,content,io,import,屌丝,Socket
来源: https://www.cnblogs.com/shan333/p/14803888.html