简体   繁体   English

Java套接字TCP发送和接收

[英]Java Sockets TCP send and receive

I tried many examples and none worked as I expect. 我尝试了许多示例,但都没有按预期工作。 What do I need? 我需要什么?

  1. Send a packet through an IP and Port. 通过IP和端口发送数据包。
  2. Wait until server response and close socket. 等待服务器响应并关闭套接字。

Example: 例:

[Client] Send: "Hi server"
[Client] Wait
[Server] Send: "Hi client"
[Client] Receive response
[Client] Close socket

I just need TCP client, server side is solved. 我只需要TCP客户端,服务器端就解决了。

Tried: http://www.careerbless.com/samplecodes/java/beginners/socket/SocketBasic1.php 尝试过: http : //www.careerbless.com/samplecodes/java/beginners/socket/SocketBasic1.php

My code 我的密码

public class SendPacket {

    public void send() throws Exception{

        Socket socket = null;
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;

        socket = new Socket(ip, port);
        oos = new ObjectOutputStream(socket.getOutputStream());

        String msg = "DSPSYSSTS";
        oos.write(msg.getBytes());
        oos.flush();

        //read the server response message
        ois = new ObjectInputStream(socket.getInputStream());
        String message = (String) ois.readObject();

        RunWinCmd runCmd = new RunWinCmd();
        runCmd.run("notepad.exe \"" + message + "\"");
        //close resources
        ois.close();
        oos.close();

    }
}

you have to initialise the streams in a particular order. 您必须按特定顺序初始化流。

try this (not tested): 试试这个(未经测试):

public class SendPacket {

    public void send() throws Exception{

        Socket socket = null;
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;

        socket = new Socket(ip, port);
        oos = new ObjectOutputStream(socket.getOutputStream());
        ois = new ObjectInputStream(socket.getInputStream());

        String msg = "DSPSYSSTS";
        oos.write(msg.getBytes());
        oos.flush();

        //read the server response message
        String message = (String) ois.readObject();

        RunWinCmd runCmd = new RunWinCmd();
        runCmd.run("notepad.exe \"" + message + "\"");
        //close resources
        ois.close();
        oos.close();
        socket.close();//!!!!

    } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM