JAVA -------- 创建TCP服务传递数据
Posted Java璐到底
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JAVA -------- 创建TCP服务传递数据相关的知识,希望对你有一定的参考价值。
话不多说直接上代码,运行的时候先启动服务端,在启动客户端
客户端:
import java.awt.BorderLayout; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.*; import java.net.Socket; import java.net.UnknownHostException; import java.nio.channels.WritableByteChannel; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.border.BevelBorder; public class Tcp_Cliect public static void main(String[] args) try //创建一个客户端socket Socket socket = new Socket("localhost",8888); //向服务器端传递信息 OutputStream ots = socket.getOutputStream(); PrintWriter pw = new PrintWriter(ots); pw.write("111222123"); pw.flush(); //关闭输出流 socket.shutdownOutput(); //获取服务器端传递的数据 InputStream is = socket.getInputStream(); InputStreamReader isr = new InputStreamReader(is,"UTF-8"); BufferedReader br = new BufferedReader(isr); String info = null; while((info=br.readLine())!=null) System.out.println("我是客户端,服务器说:"+info); //关闭资源 br.close(); isr.close(); is.close(); pw.close(); ots.close(); socket.close(); catch (UnknownHostException e) e.printStackTrace(); catch (IOException e) e.printStackTrace();
服务端:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class Tcp_service
private BufferedReader reader;
private ServerSocket serverSocket;
private Socket socket;
/**
* 创建服务端的程序,读取客户端传来的数据
*/
void getserver()
try
serverSocket = new ServerSocket(8888); //实例化服务端socket
System.out.println("服务器套接字已经创建成功");
while (true)
System.out.println("等待客户机的连接:");
socket = serverSocket.accept(); //实例化socket对象
reader = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8")); //实例化BufferReader对象
getClientMessage();
catch (Exception e)
e.printStackTrace();
private void getClientMessage()
try
String message = null;
while ((message = reader.readLine())!=null)
System.out.println("客户机传来的信息是:"+message);
OutputStreamWriter osw = new OutputStreamWriter(socket.getOutputStream(),"UTF-8");
// PrintWriter out = new PrintWriter(osw,);
PrintWriter pw = new PrintWriter(osw,true);
pw.println("服务端已接收");
catch (Exception e)
e.printStackTrace();
public static void main(String[] args)
Tcp_service myTcp = new Tcp_service(); //创建本类对象
myTcp.getserver();
以上是关于JAVA -------- 创建TCP服务传递数据的主要内容,如果未能解决你的问题,请参考以下文章