大橙子网站建设,新征程启航
为企业提供网站建设、域名注册、服务器等服务
以下是一个展示java使用tcp通讯的简单例子,包括服务器和客户端代码:
创新互联建站凭借在网站建设、网站推广领域领先的技术能力和多年的行业经验,为客户提供超值的营销型网站建设服务,我们始终认为:好的营销型网站就是好的业务员。我们已成功为企业单位、个人等客户提供了成都做网站、成都网站建设服务,以良好的商业信誉,完善的服务及深厚的技术力量处于同行领先地位。
/**
*TCPServer
*/
import java.io.*;
import java.net.*;
class TCPServer{
public static void main(String[] args)throws IOException{
ServerSocket listen = new ServerSocket(5050);
Socket server = listen.accept();
InputStream in = server.getInputStream();
OutputStream out = server.getOutputStream();
char c = (char)in.read();
System.out.println("收到:" + c);
out.write('s');
out.close();
in.close();
server.close();
listen.close();
}
}
/**
*TCPClient
*/
import java.io.*;
import java.net.*;
class TCPClient{
public static void main(String[] args)throws IOException{
Socket client = new Socket("127.0.0.1" , 5050);
InputStream in = client.getInputStream();
OutputStream out = client.getOutputStream();
out.write('c');
char c = (char)in.read();
System.out.println("收到:" + c);
out.close();
in.close();
client.close();
}
}
package com.weixin.test;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import org.junit.Test;
public class ScoketTest {
@Test
public void client() throws Exception{
InetAddress i=InetAddress.getByName("127.0.0.1");
Socket s=new Socket(i, 9000);
OutputStream outputStream = s.getOutputStream();
outputStream.write("服务端你好,我是客户端哦!".getBytes());
s.shutdownOutput();
InputStream inputStream=s.getInputStream();
int length=0;
byte[] bytes=new byte[1024];
while ((length=inputStream.read(bytes))!=-1) {
System.err.println(new String(bytes,0,length));
}
inputStream.close();
outputStream.close();
s.close();
}
@Test
public void server() throws Exception{
ServerSocket serverSocket=new ServerSocket(9000);
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
int length=0;
byte[] bytes=new byte[1024];
while ((length=inputStream.read(bytes))!=-1) {
System.err.println(new String(bytes, 0,length));
}
outputStream.write("客户端你好,本王已收到!".getBytes());
outputStream.close();
inputStream.close();
socket.close();
serverSocket.close();
}
}
写好了,有什么问题请追问。
客户端:
import java.net.*;
import java.io.*;
public class TestSocketClient {
public static void main(String[] args) {
try {
Socket socket = new Socket("127.0.0.1", 5566);
System.out.println("请输入计算式:");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s1 = br.readLine();
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
DataInputStream dis = new DataInputStream(socket.getInputStream());
dos.writeUTF(s1);
dos.flush();
double s = dis.readDouble();
System.out.println("计算结果:" + s);
dis.close();
dos.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("连接出错");
System.exit(-1);
}
}
}
服务器端:
import java.net.*;
import java.io.*;
public class TestSocketServer {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(5566);
Socket socket = ss.accept();
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
DataInputStream dis = new DataInputStream(socket.getInputStream());
String s = null;
if ((s = dis.readUTF()) != null) {
System.out.println("接收到的算式:" + s);
double result = 0;
String[] sarr1 = s.split("[\\+\\-\\*\\/]");
double a = Double.parseDouble(sarr1[0].trim());
double b = Double.parseDouble(sarr1[1].trim());
String[] sarr2 = s.split("^(-?\\d+)(\\.\\d+)?");
char c = sarr2[1].trim().charAt(0);
switch (c) {
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
result = a / b;
break;
default:
break;
}
dos.writeDouble(result);
dos.flush();
}
dis.close();
dos.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
}
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);
}
}
localhost是指你本机,它可以改成127.0.0.1,如果跟其他机器通讯就改成另一台机器的ip地址。8800是指通讯端口;
你把OS里的O理解为output,IS里的I理解为input。OS是输出端,输出端把数据放到BufferedReader,BufferedReader通过端口传输到IS后,再读取。
public static void TestModbus() throws Exception{
IpParameters params = new IpParameters();
params.setHost("localhost");//地址
params.setPort(502);//端口
ModbusFactory factory = new ModbusFactory();
ModbusMaster master = factory.createTcpMaster(params, true);
// 初始化
try {
master.init();
readHoldingRegistersTest(master,1,0,3);
} catch (ModbusInitException e) {
e.printStackTrace();
} finally {
master.destroy();
}
}
public static void main(String[] args) {
try {
TestModbus();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
private static void readHoldingRegistersTest(ModbusMaster master,
int slaveId, int start, int len) {
try {
// ReadInputRegistersRequest request = new ReadInputRegistersRequest(
// slaveId, start, len);
// ReadInputRegistersResponse response = (ReadInputRegistersResponse) master
// .send(request);
ReadHoldingRegistersRequest request = new ReadHoldingRegistersRequest(
slaveId, start, len);
ReadHoldingRegistersResponse response = (ReadHoldingRegistersResponse) master
.send(request);
if (response.isException()) {
System.out.println("Exception response: message="
+ response.getExceptionMessage());
} else {
ByteQueue byteQueue= new ByteQueue(12);
response.write(byteQueue);
System.out.println(byteQueue);
System.out.println(Arrays.toString(response.getShortData()));
short[] list = response.getShortData();
for(int i = 0; i list.length; i++){
System.out.print(list[i] + " ");
}
}
} catch (ModbusTransportException e) {
e.printStackTrace();
}
}