tcp通信java代码 tcp java
编写一个简单的TCP通信程序。服务器发送“你好我是服务器”,客户端接收该信息并显示在屏幕上。用Java写
1、服务器端
我们提供的服务有:网站设计、成都网站设计、微信公众号开发、网站优化、网站认证、叙永ssl等。为上千多家企事业单位解决了网站和推广的问题。提供周到的售前咨询和贴心的售后服务,是有科学管理、有技术的叙永网站制作公司
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServer {
private static final int PORT = 8088;
public static void main(String[] args) {
ServerSocket server = null;
try {
server = new ServerSocket(PORT);
while (true) {
Socket client = server.accept();
new Thread(new Server(client)).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Server implements Runnable {
private Socket client;
public Server(Socket client) {
this.client = client;
}
public void run() {
DataOutputStream output = null;
try {
output = new DataOutputStream(client.getOutputStream());
output.writeUTF("你好我是服务器");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (output != null) output.close();
output = null;
} catch (IOException e) {}
}
}
}
2、客户端
import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client extends Socket {
private static final int PORT = 8088;
public static void main(String[] args) {
Socket socket = null;
try {
socket = new Socket("127.0.0.1", PORT);
DataInputStream in = new DataInputStream(socket.getInputStream());
String res = in.readUTF();
System.out.println(res);
if (in != null) in.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {}
}
}
}
}
JAVA Tcp 通讯代码问题
localhost是指你本机,它可以改成127.0.0.1,如果跟其他机器通讯就改成另一台机器的ip地址。8800是指通讯端口;
你把OS里的O理解为output,IS里的I理解为input。OS是输出端,输出端把数据放到BufferedReader,BufferedReader通过端口传输到IS后,再读取。
用java编写一个能进行简单TCP/IP通信的C/S程序
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServer
{
public static void main(String[] args) throws Exception
{
// 创建服务器端的socket对象
ServerSocket ss = new ServerSocket(5000);
// 监听连接
Socket socket = ss.accept();
// 直到连接建立好之后代码才会往下执行
System.out.println("Connected Successfully!");
}
}
import java.net.Socket;
public class TcpClient
{
public static void main(String[] args) throws Exception
{
Socket socket = new Socket("127.0.0.1", 5000);
}
}
当前题目:tcp通信java代码 tcp java
本文URL:http://azwzsj.com/article/hpdscj.html