[英]How can I modify this code to allow my client socket program to send a string to the server?
Hi ive written some code to connect to a server through the use of a socket. 我已经编写了一些代码来通过使用套接字连接到服务器。 Id like to write some simple code that allows me to send a string to the server, im assuming this will involve input and output streams but I am new to this. 我想编写一些简单的代码,使我可以向服务器发送一个字符串,我假设这将涉及输入和输出流,但是我对此并不陌生。 Ive put the code I am working with below, any insights into the best way to accomplish this would be great. 我已经将我正在使用的代码放在下面,对实现此目标的最佳方法的任何见解都会很棒。
import java.net.*;
import java.io.*;
public class SocketMarket
{
public static void main(String [] args)
{
String serverName = "XX.X.X.XXX";
int port = XXXX;
try
{
System.out.println("Connecting to " + serverName + " on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Connected to " + client.getRemoteSocketAddress());
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Thanks in advance 提前致谢
client.getOutputStream().write("Hello World".getBytes());
client.getOutputStream().flush();
The above is how you would send just a String
, but you will probably want to build up some infrastructure around sending arbitrary text. 上面是仅发送String
,但是您可能希望围绕发送任意文本建立一些基础结构。
The general idea is that your server and client will communicate with each other using InputStream
's and OutputStream
's, which can be accessed from a Socket
via getInputStream()
and getOutputStream()
, once the connection between them is made. 通常的想法是,您的服务器和客户端将使用InputStream
和OutputStream
相互通信,一旦建立连接,就可以通过getInputStream()
和getOutputStream()
从Socket
访问它们。
For your server to receive connections, you should be using a ServerSocket
to accept()
incoming connections. 为了使服务器接收连接,您应该使用ServerSocket
accept()
传入连接。
Insight is here, the "really big index" for java. 洞察力在这里,是Java的“真正的大索引”。
http://docs.oracle.com/javase/tutorial/networking/sockets/readingWriting.html http://docs.oracle.com/javase/tutorial/networking/sockets/readingWriting.html
Yes, it involves OutputStream
s. 是的,它涉及OutputStream
。 If you want to output String
s you could write raw bytes via the OutputStream
you get from the connection but then you completely loose control over encoding. 如果要输出String
,则可以通过从连接中获取的OutputStream
写入原始字节,但是然后完全失去对编码的控制。 You need to learn about reader/writer/streams first, then networking via sockets is simple. 您需要首先了解阅读器/写入器/流,然后通过套接字进行网络连接很简单。 You can find the relevant part of the Java tutorials here: http://docs.oracle.com/javase/tutorial/essential/io/ (you can ignore the NIO part completely for the beginning). 您可以在这里找到Java教程的相关部分: http : //docs.oracle.com/javase/tutorial/essential/io/ (一开始您可以完全忽略NIO部分)。 After that you can learn about socket networking: http://docs.oracle.com/javase/tutorial/networking/sockets/index.html . 之后,您可以了解有关套接字网络的信息: http : //docs.oracle.com/javase/tutorial/networking/sockets/index.html 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.