服务端和客户端互聊

Posted chinaifae

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了服务端和客户端互聊相关的知识,希望对你有一定的参考价值。

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();
        }
    }
}

以上是关于服务端和客户端互聊的主要内容,如果未能解决你的问题,请参考以下文章

WebSocket服务端和客户端代码示例

Netty入门——springboot框架开发一个简单的服务器端和客户端

windows socket 简单的服务端和客户端代码

axis2的wsdl2java命令可以生成wsdl的服务端和客服端代码,请问各位大牛这个客服端和服务端的有啥区别。

SVN 服务端和客户端的安装及使用

服务器端和客户端有啥区别