我想在我的项目的窗口主机或其他主机上发布套接字服务器

【问题描述】:

我想在项目的窗口主机或其他主机上发布我的套接字服务器。但是,我找不到如何做到这一点。因为我找不到任何例子。这里有服务器和客户端,但我将使用服务器一。客户只是为了测试它。此代码也可以在 Windows 终端中运行。这是个好的观点。请帮我解决一下。

服务器.JAVA

import java.net.*;
import java.io.*;
public class Server
{
    //initialize socket and input stream
    private Socket          socket   = null;
    private ServerSocket    server   = null;
    private DataInputStream in       =  null;
    // constructor with port
    public Server(int port)
    {
        // starts server and waits for a connection
        try
        {
            server = new ServerSocket(port);
            System.out.println("Server started");
            System.out.println("Waiting for a client ...");

图片[1]-我想在我的项目的窗口主机或其他主机上发布套接字服务器-唐朝资源网

socket = server.accept(); System.out.println("Client accepted"); // takes input from the client socket in = new DataInputStream( new BufferedInputStream(socket.getInputStream())); String line = ""; // reads message from client until "Stop" is sent while (!line.equals("Stop")) { try { line = in.readUTF(); System.out.println(line); } catch(IOException i) { System.out.println(i); } } System.out.println("Closing connection"); // close connection socket.close(); in.close(); } catch(IOException i) { System.out.println(i); } } public static void main(String args[]) { Server server = new Server( 5000); } }

Client.java

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

public class Client
{
    // initialize socket and input output streams
    private Socket socket            = null;
    private DataInputStream  input   = null;
    private DataOutputStream out     = null;
    // constructor to put ip address and port
    public Client(String address, int port)
    {
        // establish a connection
        try
        {
            socket = new Socket(address, port);
            System.out.println("Connected");
            // takes input from terminal
            input  = new DataInputStream(System.in);
            // sends output to the socket
            out    = new DataOutputStream(socket.getOutputStream());
        }

        catch(UnknownHostException u)
        {
            System.out.println(u);
        }
        catch(IOException i)
        {
            System.out.println(i);
        }
        // string to read message from input
        String line = "";
        // keep reading until "Stop" is input
        while (!line.equals("Stop"))
        {
            try
            {
                line = input.readLine();
                out.writeUTF(line);
            }
            catch(IOException i)
            {
                System.out.println(i);

图片[2]-我想在我的项目的窗口主机或其他主机上发布套接字服务器-唐朝资源网

} } // close the connection try { input.close(); out.close(); socket.close(); } catch(IOException i) { System.out.println(i); } } public static void main(String args[]) { Client client = new Client("127.0.0.1", 5000); } }

【讨论】:

© 版权声明
THE END
喜欢就支持一下吧
点赞233赞赏 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容