java写socket(java写文件)

华为云服务器特价优惠火热进行中!

2核2G2兆仅需 38 元;4核4G3兆仅需 79 元。购买时间越长越优惠!更多配置及优惠价格请咨询客服。

合作流程:
1、点击链接注册/关联华为云账号:点击跳转
2、添加客服微信号:cloud7591,确定产品方案、价格方案、服务支持方案等;
3、客服协助购买,并拉微信技术服务群,享受一对一免费技术支持服务;
技术专家在金蝶、华为、腾讯原厂有多年工作经验,并已从事云计算服务8年,可对域名、备案、网站搭建、系统部署、AI人工智能、云资源规划等上云常见问题提供更专业靠谱的服务,对相应产品提供更优惠的报价和方案,欢迎咨询。

今天给各位分享java写socket的知识,其中也会对java写文件进行解释,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!

微信号:cloud7591
如需了解更多,欢迎添加客服微信咨询。
复制微信号

本文目录一览:

如何使用java socket来传输自定义的数据包?

以下分四点进行描述:

1,什么是Socket

网络上的两个程序通过一个双向的通讯连接实现数据的交换,这个双向链路的一端称为一个Socket。Socket通常用来实现客户方和服务方的连接。Socket是TCP/IP协议的一个十分流行的编程界面,一个Socket由一个IP地址和一个端口号唯一确定。

但是,Socket所支持的协议种类也不光TCP/IP一种,因此两者之间是没有必然联系的。在Java环境下,Socket编程主要是指基于TCP/IP协议的网络编程。

2,Socket通讯的过程

Server端Listen(监听)某个端口是否有连接请求,Client端向Server 端发出Connect(连接)请求,Server端向Client端发回Accept(接受)消息。一个连接就建立起来了。Server端和Client 端都可以通过Send,Write等方法与对方通信。

对于一个功能齐全的Socket,都要包含以下基本结构,其工作过程包含以下四个基本的步骤:

(1) 创建Socket;

(2) 打开连接到Socket的输入/出流;

(3) 按照一定的协议对Socket进行读/写操作;

(4) 关闭Socket.(在实际应用中,并未使用到显示的close,虽然很多文章都推荐如此,不过在我的程序中,可能因为程序本身比较简单,要求不高,所以并未造成什么影响。)

3,创建Socket

创建Socket

java在包java.net中提供了两个类Socket和ServerSocket,分别用来表示双向连接的客户端和服务端。这是两个封装得非常好的类,使用很方便。其构造方法如下:

Socket(InetAddress address, int port);

Socket(InetAddress address, int port, boolean stream);

Socket(String host, int prot);

Socket(String host, int prot, boolean stream);

Socket(SocketImpl impl)

Socket(String host, int port, InetAddress localAddr, int localPort)

Socket(InetAddress address, int port, InetAddress localAddr, int localPort)

ServerSocket(int port);

ServerSocket(int port, int backlog);

ServerSocket(int port, int backlog, InetAddress bindAddr)

其中address、host和port分别是双向连接中另一方的IP地址、主机名和端 口号,stream指明socket是流socket还是数据报socket,localPort表示本地主机的端口号,localAddr和 bindAddr是本地机器的地址(ServerSocket的主机地址),impl是socket的父类,既可以用来创建serverSocket又可 以用来创建Socket。count则表示服务端所能支持的最大连接数。例如:学习视频网

Socket client = new Socket("127.0.01.", 80);

ServerSocket server = new ServerSocket(80);

注意,在选择端口时,必须小心。每一个端口提供一种特定的服务,只有给出正确的端口,才 能获得相应的服务。0~1023的端口号为系统所保留,例如http服务的端口号为80,telnet服务的端口号为21,ftp服务的端口号为23, 所以我们在选择端口号时,最好选择一个大于1023的数以防止发生冲突。

在创建socket时如果发生错误,将产生IOException,在程序中必须对之作出处理。所以在创建Socket或ServerSocket是必须捕获或抛出例外。

4,简单的Client/Server程序

1. 客户端程序

import java.io.*;

import java.net.*;

public class TalkClient {

public static void main(String args[]) {

try{

Socket socket=new Socket("127.0.0.1",4700);

//向本机的4700端口发出客户请求

BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));

//由系统标准输入设备构造BufferedReader对象

PrintWriter os=new PrintWriter(socket.getOutputStream());

//由Socket对象得到输出流,并构造PrintWriter对象

BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));

//由Socket对象得到输入流,并构造相应的BufferedReader对象

String readline;

readline=sin.readLine(); //从系统标准输入读入一字符串

while(!readline.equals("bye")){

//若从标准输入读入的字符串为 "bye"则停止循环

os.println(readline);

//将从系统标准输入读入的字符串输出到Server

os.flush();

//刷新输出流,使Server马上收到该字符串

System.out.println("Client:"+readline);

//在系统标准输出上打印读入的字符串

System.out.println("Server:"+is.readLine());

//从Server读入一字符串,并打印到标准输出上

readline=sin.readLine(); //从系统标准输入读入一字符串

} //继续循环

os.close(); //关闭Socket输出流

is.close(); //关闭Socket输入流

socket.close(); //关闭Socket

}catch(Exception e) {

System.out.println("Error"+e); //出错,则打印出错信息

}

}

}

 2. 服务器端程序

import java.io.*;

import java.net.*;

import java.applet.Applet;

public class TalkServer{

public static void main(String args[]) {

try{

ServerSocket server=null;

try{

server=new ServerSocket(4700);

//创建一个ServerSocket在端口4700监听客户请求

}catch(Exception e) {

System.out.println("can not listen to:"+e);

//出错,打印出错信息

}

Socket socket=null;

try{

socket=server.accept();

//使用accept()阻塞等待客户请求,有客户

//请求到来则产生一个Socket对象,并继续执行

}catch(Exception e) {

System.out.println("Error."+e);

//出错,打印出错信息

}

String line;

BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));

 //由Socket对象得到输入流,并构造相应的BufferedReader对象

PrintWriter os=newPrintWriter(socket.getOutputStream());

 //由Socket对象得到输出流,并构造PrintWriter对象

BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));

 //由系统标准输入设备构造BufferedReader对象

System.out.println("Client:"+is.readLine());

//在标准输出上打印从客户端读入的字符串

line=sin.readLine();

//从标准输入读入一字符串

while(!line.equals("bye")){

//如果该字符串为 "bye",则停止循环

os.println(line);

//向客户端输出该字符串

os.flush();

//刷新输出流,使Client马上收到该字符串

System.out.println("Server:"+line);

//在系统标准输出上打印读入的字符串

System.out.println("Client:"+is.readLine());

//从Client读入一字符串,并打印到标准输出上

line=sin.readLine();

//从系统标准输入读入一字符串

}  //继续循环

os.close(); //关闭Socket输出流

is.close(); //关闭Socket输入流

socket.close(); //关闭Socket

server.close(); //关闭ServerSocket

}catch(Exception e){

System.out.println("Error:"+e);

//出错,打印出错信息

}

}

}

Java 编写 Socket服务器与客户端时出现的理解上的问题

基于你的这段代码 看起来像是client段的输出 其实不是的 ,

PrintStream pout=new PrintStream(Client.getOutPutStream);这个Client 是一个socket类 并不是代表是client的输出流 而是server段 socket的输出流。

看代码:

server端:

servSocket = new ServerSocket(port);

socket = server.accept();

sin = new DataInputStream( socket.getInputStream());

sout = new DataOutputStream (socket.getOutputStream());

client端:

socket = new Socket(host,port);

cin = new DataInputStream( socket.getOutputStream());

cout = new DataOutputStream (socket.getOutputStream());

连接后 server的sin 接受cout,client 端的cin 接受sout

你的那个Client.getOutPutStream是在server端 的 相当于我这个

sout = new DataOutputStream (socket.getOutputStream());

java中如何创建socket连接的过程

这是我写过的一个简单聊天软件客户端  你参考下

import java.util.*;

import java.io.*;

import java.net.*;

import java.awt.*;

import javax.swing.*;

import java.awt.event.*;

public class testChatClient extends JFrame

{

private JTextArea jta = new JTextArea();

private JTextField jtf = new JTextField();

private JComboBoxString jcb = new JComboBoxString();

private JButton jbsend = new JButton("send");

private JButton jbrefresh = new JButton("refresh");

private InputStream input;

private OutputStream output;

private Socket socket;

public static String SERVER_IP = "192.168.1.101";

public static int SERVER_PORT = 8888;

// Message 1 - refresh message

// Message 2 - send message

public testChatClient()

{

initComponents();

try

{

socket = new Socket(SERVER_IP,SERVER_PORT);

input = socket.getInputStream();

output = socket.getOutputStream();

}

catch(IOException e)

{

System.err.println(e);

}

jbrefresh.addActionListener(new ActionListener()

{

public void actionPerformed(ActionEvent e)

{

jta.setText("");

try

{

if(socket == null)

socket = new Socket(SERVER_IP,SERVER_PORT);

output.write(0x31);

catch (IOException ex)

{

JOptionPane.showConfirmDialog(null, ex);

}

}

});

jbsend.addActionListener(new ActionListener()

{

public void actionPerformed(ActionEvent e)

{

if(jtf.getText() == null || jtf.getText().equals(""))

return;

if(jtf.getText().length() = 400)

{

JOptionPane.showConfirmDialog(null,"最大字数不能超过400");

return;

}

try

{

String destination = jcb.getSelectedItem().toString();

String message = jtf.getText();

if(socket == null)

socket = new Socket(SERVER_IP,SERVER_PORT);

byte[] temp = new byte[3 + destination.getBytes().length + message.getBytes().length];

temp[0] = 0x32;

temp[1] = (byte)destination.getBytes().length;

int i = 2;

for(int j = 0; j  destination.getBytes().length ; i++ , j++)

temp[i] = destination.getBytes()[j];

temp[i++] = (byte)message.getBytes().length;

for(int j = 0 ; j  message.getBytes().length ; i++ , j++)

{

temp[i] = message.getBytes()[j];

System.out.println();

}

output.write(temp);

jta.append("me:\n");

jta.append(jtf.getText());

jta.append("\n");

jtf.setText("");

}

catch(IOException ex)

{

System.err.println(ex);

}

}

});

try

{

jbrefresh.doClick();

while(true)

{

byte[] tempBytes = new byte[1000];

input.read(tempBytes);

int command = tempBytes[0] - 0x30;

// int readLength = input.read();

switch(command)

{

case 1:

{

int readLength = tempBytes[1];

String[] temp = new String(tempBytes,2,readLength,"UTF-8").split(";");

jcb.removeAllItems();

if(temp.length == 0  temp[0].equals(""))

return;

for(int i = 0 ; i  temp.length ;i++)

{

jcb.addItem(temp[i]);

}

jcb.setSelectedIndex(0);

break;

}

case 2:

{

int readLength1 = tempBytes[1];

jta.append(new String(tempBytes,2,readLength1,"UTF-8") + "\n");

int readLength2 = tempBytes[2 + readLength1];

jta.append(new String(tempBytes,3 + readLength1,readLength2,"UTF-8") + "\n");

break;

}

}

}

}

catch(IOException e)

{

System.err.println(e);

}

}

public static void main(String[] args) {

testChatClient frame = new testChatClient();

}

public void initComponents()

{

setLayout(new BorderLayout());

JPanel jpNorth = new JPanel();

jpNorth.setLayout(new BorderLayout());

jpNorth.add(jcb,BorderLayout.CENTER);

jpNorth.add(jbrefresh,BorderLayout.EAST);

JPanel jpSouth = new JPanel();

jpSouth.setLayout(new BorderLayout());

jpSouth.add(jtf,BorderLayout.CENTER);

jpSouth.add(jbsend,BorderLayout.EAST);

add(jpNorth,BorderLayout.NORTH);

add(jpSouth,BorderLayout.SOUTH);

add(new JScrollPane(jta),BorderLayout.CENTER);

this.getRootPane().setDefaultButton(jbsend);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setSize(300,600);

setVisible(true);

}

}

JAVA问题:用socket编写一个服务器端程序

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.ServerSocket;

import java.net.Socket;

publicclass Server

{

private ServerSocket ss;

private Socket socket;

private BufferedReader in;

private PrintWriter out;

public Server()

{

try

{

ss = new ServerSocket(10000);

while (true)

{

socket = ss.accept();

String RemoteIP = socket.getInetAddress().getHostAddress();

String RemotePort = ":" + socket.getLocalPort();

System.out.println("A clientcome in!IP:" + RemoteIP

+ RemotePort);

in = new BufferedReader(new

InputStreamReader(socket.getInputStream()));

String line = in.readLine();

System.out.println("Cleint sendis :" + line);

out = new PrintWriter(socket.getOutputStream(), true);

out.println("YourMessage Received!");

out.close();

in.close();

socket.close();

}

}

catch (IOException e)

{

out.println("wrong");

}

}

publicstaticvoid main(String[] args)

{

new Server();

}

}

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.Socket;

publicclass Client {

Socket socket;

BufferedReader in;

PrintWriter out;

public Client()

{

try

{

System.out.println("Try toConnect to 127.0.0.1:10000");

socket = new Socket("127.0.0.1", 10000);

System.out.println("The ServerConnected!");

System.out.println("Pleaseenter some Character:");

BufferedReader line = new BufferedReader(new

InputStreamReader(System.in));

out = new PrintWriter(socket.getOutputStream(), true);

out.println(line.readLine());

in = new BufferedReader(new InputStreamReader(socket

.getInputStream()));

System.out.println(in.readLine());

out.close();

in.close();

socket.close();

}

catch (IOException e)

{

out.println("Wrong");

}

}

publicstaticvoid main(String[] args)

{

new Client();

}

}

你再改改代码就可以了.但我没时间帮你调了……

java或者scala写socket客户端发送头消息和消息体到服务端并接收返回信息,这个头消息怎么写

import java.io.BufferedReader;

import java.io.DataInputStream;

import java.io.DataOutputStream;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.Socket;

public class Client {

public static final String IP_ADDR = "localhost";//服务器地址

public static final int PORT = 12345;//服务器端口号

public static void main(String[] args) {

System.out.println("客户端启动...");

System.out.println("当接收到服务器端字符为 \"OK\" 的时候, 客户端将终止\n");

while (true) {

Socket socket = null;

try {

//创建一个流套接字并将其连接到指定主机上的指定端口号

socket = new Socket(IP_ADDR, PORT);

//读取服务器端数据

DataInputStream input = new DataInputStream(socket.getInputStream());

//向服务器端发送数据

DataOutputStream out = new DataOutputStream(socket.getOutputStream());

System.out.print("请输入: \t");

String str = new BufferedReader(new InputStreamReader(System.in)).readLine();

out.writeUTF(str);

String ret = input.readUTF();

System.out.println("服务器端返回过来的是: " + ret);

// 如接收到 "OK" 则断开连接

if ("OK".equals(ret)) {

System.out.println("客户端将关闭连接");

Thread.sleep(500);

break;

}

out.close();

input.close();

} catch (Exception e) {

System.out.println("客户端异常:" + e.getMessage());

} finally {

if (socket != null) {

try {

socket.close();

} catch (IOException e) {

socket = null;

System.out.println("客户端 finally 异常:" + e.getMessage());

}

}

}

}

}

}

java中socket实现两天电脑连接IP怎么写啊? 求高手指点

Socket

分为服务器端和客户端

连接时,服务器端用某个端口打开socket,然后监听

客户端用ip和端口连接,被接收则连接成功。

因此,服务器端(你可以随意指定一个电脑为服务器端

)打开端口连接:

ServerSocket

serversocket

=

new

ServerSocket(port);

Socket

socket

=

serverSocket.accept();//监听客户端的连接

然后客户端:

Socket

socket=new

Socket(ip,port);//这里的ip也可以用域名

希望对你有所帮助~

关于java写socket和java写文件的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。

发布于 2023-04-02 22:04:22
收藏
分享
海报
35
目录

    忘记密码?

    图形验证码

    复制成功
    微信号: cloud7591
    如需了解更多,欢迎添加客服微信咨询。
    我知道了