使用套接字的双向Java聊天

时间:2014-04-16 09:09:44

标签: java sockets

我试图找到一些类似于帮助我使用我的代码的东西,我也尝试自己做,但我最终陷入困境,如果有人能帮助我,我真的很感激。

所以我已经使用了简单的Java客户端/服务器代码,我想要做的就是升级它以便它可以双向工作,现在在启动服务器并通过客户端连接到它之后你写的所有内容客户端也将显示在服务器上,我想升级它,所以我在客户端上写的内容将显示在服务器上,我在服务器上写的内容将显示在客户端上。

myServer.java

import java.io.*;
import java.net.*;

public class myServer {
    public static void main (String[] args) {
        try {
           int i=0;
           ServerSocket ss = new ServerSocket(9000);
           System.out.println("Listening...");
           Socket s = ss.accept();
           System.out.println("Connection accepted");
           InputStream d1 = s.getInputStream();


            while ((char)i !='q')
        {    
            i = d1.read();
            System.out.print((char)i);

        }
           s.close();
           ss.close();
        } catch (Exception e) {System.out.println("Error"); } 

    }
}

myClient.java

import java.io.*;
import java.net.*;

public class myClient {
public static void main(String[] args) {
    try {
        int i=0;
        Socket s=new Socket("localhost",9000);
        OutputStream o = s.getOutputStream();


        while ((char)i !='q')
        {
            i = System.in.read();
            o.write((char)i);

        }
        s.close();      
    } catch(Exception e) {System.out.println("Error"); }



    }
}

提前谢谢你。

0 个答案:

没有答案