精华内容
下载资源
问答
  • Java 套接字编程Java 套接字编程Java 套接字编程Java 套接字编程Java 套接字编程Java 套接字编程
  • 客户端import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.InetAddress;import java.net.Socket;import java.net....

    客户端

    import java.io.BufferedReader;

    import java.io.IOException;

    import java.io.InputStreamReader;

    import java.io.PrintWriter;

    import java.net.InetAddress;

    import java.net.Socket;

    import java.net.UnknownHostException;

    public class MultiJabberClient {

    static final int MAX_THREADS = 10;

    public void start() throws UnknownHostException, InterruptedException {

    InetAddress addr = InetAddress.getByName("bupt"); // 主机名

    while (true) {

    if (JabberClientThread.getThreadCount() < MAX_THREADS)

    new JabberClientThread(addr); // addr是服务器的地址

    }

    }

    public static void main(String args[]) throws UnknownHostException,

    InterruptedException {

    new MultiJabberClient().start();

    }

    }

    class JabberClientThread extends Thread {

    private static int counter = 0;

    private static int threadcount = 0;

    private int id = counter++;

    private Socket socket;

    private BufferedReader in;

    private PrintWriter out;

    public JabberClientThread(InetAddress addr) {

    System.out.println("Making Client " + id);

    threadcount++;

    try {

    socket = new Socket(addr, MultiJabberServer.PORT);

    } catch (IOException e) {

    e.printStackTrace();

    }

    try {

    in = new BufferedReader(new InputStreamReader(socket

    .getInputStream()));

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

    start();

    } catch (IOException e) {

    e.printStackTrace();

    try {

    socket.close();

    } catch (IOException e1) {

    e1.printStackTrace();

    }

    }

    }

    public void run() {

    try {

    out.println("hello");

    out.println("bye");

    String str = in.readLine();

    System.out.println(str);

    // }

    out.println("END");

    } catch (Exception e) {

    e.printStackTrace();

    } finally {

    System.out.println("Client " + id + " closing...");

    try {

    socket.close();

    } catch (IOException e) {

    e.printStackTrace();

    }

    threadcount--;

    }

    }

    public static int getThreadCount() {

    return threadcount;

    }

    }

    服务器端

    import java.io.BufferedReader;

    import java.io.IOException;

    import java.io.InputStreamReader;

    import java.io.PrintWriter;

    import java.net.ServerSocket;

    import java.net.Socket;

    public class MultiJabberServer {

    public static final int PORT = 8080; //端口可以任意指定大于1024的端口号

    public void start() throws IOException{

    ServerSocket s = new ServerSocket(PORT);

    System.out.println("Server started.");

    try{

    while(true){

    final Socket socket = s.accept();//阻塞,直到建立一个连接,通常,阻塞是由循环产生的。

    try{

    new ServerOneJabber(socket); //监听到一个端口,就新建一个线程进行执行

    }

    catch(Exception e){

    socket.close();

    }

    }

    }

    finally{

    s.close();

    }

    }

    public static void main(String args[]) throws IOException{

    new MultiJabberServer().start();

    }

    }

    class ServerOneJabber extends Thread{

    private Socket socket;

    private BufferedReader in;

    private PrintWriter out;

    public ServerOneJabber(Socket s) throws IOException{

    socket = s;

    in = new BufferedReader(

    new InputStreamReader(socket.getInputStream())); //负责读取来自客户端的请求

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

    用来向客户端会送响应的

    start();

    }

    public void run() {

    System.out.println(socket.getInetAddress()+":"+socket.getPort());

    try{

    while(true){

    String str = in.readLine(); //从客户端读取的字符串

    if(str.equals("END"))

    break;

    System.out.println("Echoing: " + str);

    out.println(str);

    }

    }

    catch (IOException e) {

    e.printStackTrace();

    }

    finally{

    System.out.println("closing...");

    try {

    socket.close();

    } catch (IOException e) {

    e.printStackTrace();

    }

    }

    }

    }

    展开全文
  • 在高层次上,有一些事情需要解决 . 鉴于帖子中的代码有一个服务器,它启动与客户端的通信,需要修改行(以及相关代码)在服务器端:sendto(udpSocket,buffer,buflen,0,(struct sockaddr *)&serverStorage,addr_...

    在高层次上,有一些事情需要解决 . 鉴于帖子中的代码有一个服务器,它启动与客户端的通信,需要修改行(以及相关代码)

    在服务器端:

    sendto(udpSocket,buffer,buflen,0,(struct sockaddr *)&serverStorage,addr_size);

    基本上这里发生的是udpSocket绑定到serverAddr,我们正在尝试发送到serverStorage(第二个参数) . 这里的问题是serverStorage没有绑定任何东西 . 基本上sendto有源权限但不是目的地 .

    在客户端:

    recvfrom(clientSocket,buffer,buflen,0,(struct sockaddr *)&serverAddr, &addr_size);

    clientSocket没有绑定任何东西,因此系统会选择一个随机端口来监听它 . 在recvfrom调用中,第二个参数捕获另一方的地址详细信息 . 在代码中,您已将其绑定到服务器的IP和端口,但它没有任何效果,因为它由recvfrom调用填充并返回 .

    为了使事情在这里工作是我的建议(你可以添加细节,但已根据你发布的内容计算出骨架)

    server_initiating_with_client.c

    //...

    int udpSocket, nBytes, buflen;

    char buffer[1024];

    int portNum;

    struct sockaddr_in serverAddr, clientAddr;

    struct sockaddr_storage serverStorage;

    socklen_t addr_size, client_addr_size;

    /*Create UDP socket*/

    udpSocket = socket(AF_INET, SOCK_DGRAM, 0);

    portNum=atoi(argv[1]);

    /*Configure settings in address struct*/

    memset(&serverAddr, 0, sizeof(serverAddr));

    serverAddr.sin_family = AF_INET;

    serverAddr.sin_port = htons(5000); // Making sure server has a unique port number

    serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);

    /*Bind socket with address struct*/

    int bStatus = bind(udpSocket, (struct sockaddr *) &serverAddr, sizeof(serverAddr));

    if (bStatus < 0) {

    printf("error binding on server's port number\n");

    exit(1);

    }

    /*Initialize size variable to be used later on*/

    addr_size = sizeof serverStorage;

    /* Because server is initiating the communication here one needs to set the

    * clientAddr and needs to know the port number of the client

    */

    memset(&clientAddr, 0, sizeof(clientAddr));

    clientAddr.sin_family = AF_INET;

    clientAddr.sin_port = htons(portNum);

    clientAddr.sin_addr.s_addr = htonl(INADDR_ANY);

    while(1){

    sprintf(buffer,"Hello Client");

    buflen=strlen(buffer);

    int bytesSent = sendto(udpSocket,buffer,buflen, 0,

    (struct sockaddr *)&clientAddr,

    sizeof(clientAddr));

    if (bytesSent < 0) {

    printf("Error sending/ communicating with client\n");

    exit(1);

    }

    printf("Done sending %s\n", buffer);

    sleep(1);

    }

    ..

    在客户端,这些方面的东西

    //..

    int clientSocket, portNum, nBytes, buflen;

    char buffer[1024];

    struct sockaddr_in serverAddr;

    struct sockaddr_in clientAddr;

    socklen_t addr_size;

    /*Create UDP socket*/

    clientSocket = socket(PF_INET, SOCK_DGRAM, 0);

    portNum = atoi(argv[1]);

    /*Configure settings in address struct*/

    memset(&clientAddr, 0, sizeof(clientAddr));

    clientAddr.sin_family = AF_INET;

    clientAddr.sin_port = htons(portNum);

    clientAddr.sin_addr.s_addr = htonl(INADDR_ANY);

    memset(&serverAddr, 0, sizeof(serverAddr));

    /*Bind on client side as well because you are specifically sending something over

    * to the client. Usually the server will know where to talk back to the client

    * but in your example because of the reversed semantics this will be needed

    */

    bind(clientSocket, (struct sockaddr *) &clientAddr, sizeof(clientAddr));

    /*Initialize size variable to be used later on*/

    addr_size = sizeof serverAddr;

    while(1){

    memset(buffer, 0, 1024);

    buflen=65536;

    recvfrom(clientSocket,buffer,buflen,0,(struct sockaddr *)&serverAddr, &addr_size);

    printf("Received from server: %s\n",buffer);

    sleep(1);

    }

    return 0;

    如果您将通信从客户端转换为服务器,则可以简化代码,从而消除客户端上固定端口号的需要 .

    展开全文
  • 超级简单,没有太多实质内容的Socket服务端,客户端小程序先运行server 再运行client OK服务端代码如下:public class Server {public static void main(String[] args) {try {ServerSocket server = new ...

    超级简单,没有太多实质内容的Socket服务端,客户端小程序

    先运行server 再运行client OK

    服务端代码如下:public class Server {

    public static void main(String[] args) {

    try {

    ServerSocket server = new ServerSocket(8800);

    Socket socket = server.accept();

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

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

    String info = null;

    while((info=br.readLine())!=null){

    System.out.println("客户端:"+info);

    }

    pw.write("我是服务器!");

    pw.flush();

    pw.close();

    br.close();

    socket.close();

    } catch (IOException e) {

    e.printStackTrace();

    }

    }

    由最代码官方编辑于2014-10-15 9:30:59

    展开全文
  • 运行效果:===============================================================服务器端代码:package ...import java.io.*;import java.net.*;import java.awt.*;import java.awt.event.*;/*...

    运行效果:

    e723775f4f858c6c7510f66e9f1d8c34.png

    ===============================================================

    服务器端代码:

    package com.b510.socket1706.gui.freeechatroom;

    import java.io.*;

    import java.net.*;

    import java.awt.*;

    import java.awt.event.*;

    /**

    * 服务器端程序

    *

    * @author Hongten

    *

    * @time 2012-4-29 2012

    */

    public class TestServer {

    private ServerSocket ss;

    private Socket s;

    private DataInputStream dis;

    private DataOutputStream dos;

    private TextArea ta;

    private TextField tf;

    public static void main(String args[]) {

    TestServer ts = new TestServer();

    ts.createUI();

    ts.connect();

    ts.createThread();

    }

    public void connect() {

    try {

    ss = new ServerSocket(8888);

    s = ss.accept();

    dis = new DataInputStream(s.getInputStream());

    dos = new DataOutputStream(s.getOutputStream());

    } catch (IOException e) {

    e.printStackTrace();

    // 13701303436

    }

    }

    public void createUI() {

    Frame f = new Frame("Server");

    ta = new TextArea();

    tf = new TextField();

    Button send = new Button("send");

    Panel p = new Panel();

    p.setLayout(new BorderLayout());

    p.add(tf, "Center");

    p.add(send, "East");

    f.add(ta, "Center");

    f.add(p, "South");

    MyServerListener listener = new MyServerListener(this);

    send.addActionListener(listener);

    tf.addActionListener(listener);

    f.addWindowListener(new WindowAdapter() {

    public void windowClosing(WindowEvent e) {

    System.exit(0);

    }

    });

    f.setSize(400, 400);

    f.setVisible(true);

    }

    public void createThread() {

    MyServerReader reader = new MyServerReader(this);

    reader.start();

    }

    public void close() {

    try {

    dis.close();

    dos.close();

    s.close();

    ss.close();

    } catch (IOException e) {

    e.printStackTrace();

    }

    }

    public DataInputStream getDataInputStream() {

    return dis;

    }

    public DataOutputStream getDataOutputStream() {

    return dos;

    }

    public TextArea getTextArea() {

    return ta;

    }

    public TextField getTextField() {

    return tf;

    }

    }

    class MyServerListener implements ActionListener {

    private TestServer server;

    public MyServerListener(TestServer server) {

    this.server = server;

    }

    public void actionPerformed(ActionEvent e) {

    TextField tf = server.getTextField();

    String info = tf.getText();

    server.getTextArea().append("自己说: " + info + "\n");

    try {

    server.getDataOutputStream().writeUTF(info);

    } catch (IOException e1) {

    e1.printStackTrace();

    }

    if (info.equals("bye")) {

    server.close();

    System.exit(0);

    }

    tf.setText("");

    tf.requestFocus();

    }

    }

    class MyServerReader extends Thread {

    private TestServer server;

    public MyServerReader(TestServer server) {

    this.server = server;

    }

    public void run() {

    String info;

    DataInputStream dis = server.getDataInputStream();

    TextArea ta = server.getTextArea();

    try {

    while (true) {

    info = dis.readUTF();

    ta.append("对方说: " + info + "\n");

    if (info.equals("bye")) {

    server.close();

    System.exit(0);

    }

    }

    } catch (IOException e) {

    e.printStackTrace();

    }

    }

    }

    客户端代码:

    package com.b510.socket1706.gui.freeechatroom;

    import java.io.*;

    import java.net.*;

    import java.awt.*;

    import java.awt.event.*;

    /**

    * 客户端程序

    * @author Hongten

    *

    * @time 2012-4-29 2012

    */

    public class TestClient {

    private Socket s;

    private DataInputStream dis;

    private DataOutputStream dos;

    private TextArea ta;

    private TextField tf;

    public static void main(String args[]) {

    TestClient tc = new TestClient();

    tc.createUI();

    tc.connect();

    tc.createThread();

    }

    public void connect() {

    try {

    s = new Socket("127.0.0.1", 8888);

    dos = new DataOutputStream(s.getOutputStream());

    dis = new DataInputStream(s.getInputStream());

    } catch (IOException e) {

    e.printStackTrace();

    }

    }

    public void createUI() {

    Frame f = new Frame("Client");

    ta = new TextArea();

    tf = new TextField();

    Button send = new Button("send");

    Panel p = new Panel();

    p.setLayout(new BorderLayout());

    p.add(tf, "Center");

    p.add(send, "East");

    f.add(ta, "Center");

    f.add(p, "South");

    MyClientListener listener = new MyClientListener(this);

    send.addActionListener(listener);

    tf.addActionListener(listener);

    f.addWindowListener(new WindowAdapter() {

    public void windowClosing(WindowEvent e) {

    System.exit(0);

    }

    });

    f.setSize(400, 400);

    f.setLocation(600, 0);

    f.setVisible(true);

    }

    public void createThread() {

    MyClientReader reader = new MyClientReader(this);

    reader.start();

    }

    public void close() {

    try {

    dis.close();

    dos.close();

    s.close();

    } catch (IOException e) {

    e.printStackTrace();

    }

    }

    public DataInputStream getDataInputStream() {

    return dis;

    }

    public DataOutputStream getDataOutputStream() {

    return dos;

    }

    public TextArea getTextArea() {

    return ta;

    }

    public TextField getTextField() {

    return tf;

    }

    }

    class MyClientListener implements ActionListener {

    private TestClient client;

    public MyClientListener(TestClient client) {

    this.client = client;

    }

    public void actionPerformed(ActionEvent e) {

    TextField tf = client.getTextField();

    String info = tf.getText();

    client.getTextArea().append("自己说: " + info + "\n");

    try {

    client.getDataOutputStream().writeUTF(info);

    } catch (IOException e1) {

    e1.printStackTrace();

    }

    if (info.equals("bye")) {

    client.close();

    System.exit(0);

    }

    tf.setText("");

    tf.requestFocus();

    }

    }

    class MyClientReader extends Thread {

    private TestClient client;

    public MyClientReader(TestClient client) {

    this.client = client;

    }

    public void run() {

    String info;

    DataInputStream dis = client.getDataInputStream();

    TextArea ta = client.getTextArea();

    try {

    while (true) {

    info = dis.readUTF();

    ta.append("对方说: " + info + "\n");

    if (info.equals("bye")) {

    client.close();

    System.exit(0);

    }

    }

    } catch (IOException e) {

    e.printStackTrace();

    }

    }

    }

    有关于socket的简单编程基础,大家可以参考:

    https://www.cnblogs.com/hongten/category/358059.html

    展开全文
  • TCP套接字编程 java原生

    千次阅读 2014-12-16 17:42:27
    import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; import org.w3c.do
  • Socket套接字—Java套接字编程
  • java套接字编程 本教程是Java套接字编程的简介,从一个简单的客户机-服务器示例开始,该示例演示了Java I / O的基本功能。 将向您介绍原始的java.io软件包和NIO,即Java 1.4中引入的非阻塞I / O( java.nio )API。 ...
  • socket 套接字 Java 套接字 编程 socket 套接字 Java 套接字 编程 socket 套接字 Java 套接字 编程 socket 套接字 Java 套接字 编程
  • 本文介绍了一种非常基本的单向客户端和服务器设置,其中客户端...客户端编程建立套接字连接要连接到其他机器,我们需要一个套接字连接。套接字连接意味着两台机器有关于彼此的网络位置(IP地址)和TCP端口的信息.java...
  • JAVA套接字之TCP编程1 TCP协议TCP是面向谅解的协议。所谓连接,就是两个对等实体为进行数据通信而进行的一种结合。面向连接服务是在数据交换之前,必须先建立连接。当数据交换结束后,则应终止这个连接。面向连接...
  • 在这篇文章中我们将介绍套接字(Socket)慨念,同时以实例说明如何使用Network API操纵套接字,在完成本文后,你就可以编写网络低端通讯软件。什么是套接字(Socket)?Network API是典型的用于基于TC...
  • java套接字编程 网络和套接字编程Java编程语言最重要的领域之一,对于在基于客户端/服务器的应用程序中工作的程序员而言,尤其如此。 对重要协议(例如TCP和UDP)的详细了解非常重要,尤其是如果您从事编写通过...
  • 自寻址套接字(Datagram Sockets)因为使用流套接字的每个连接均要花费一定的时间,要减少这种开销,网络API提供了第二种套接字:自寻址套接字(datagram socket),自寻址使用UDP发送寻址信息(从客户程序到服务程序或从...
  • 小编典典问题在于您创建流的顺序:在文章(我假设您正在使用的服务器)中的服务器中,当打开新连接时,服务器首先打开一个输入流,然后打开一个输出流:public Connect(Socket clientSocket) {client = clientSocket;...
  • 实现了基于TCP的Java Socket编程实例代码:简单实现了服务器和客户端的套接字编程,并传递简单的字符串。(在服务器声明套接字时需要绑定服务器的端口,端口为临界资源只能一个套接字使用。服务器编程时调用accept()...
  • JAVA网络编程资料(1)-Socket套接字—Java套接字编程.chm
  • Java套接字编程

    2014-03-20 22:15:43
    Java套接字编程,关于java套接字的编程文档
  • 相对于C和C++来说,Java中的socket编程是比较简单的,比较多的细节都已经被封装好了,每次创建socket连接只需要知道地址和端口即可。在了解socket编程之前,我们先来了解一下读写数据的数据流类中一些需要注意的东西...
  • 服务器server.javapackage socket;import java.io.*;import java.net.*;public class server {public static void main(String args[]) {try{ServerSocket server=null;try{//创建一个ServerSocket在端口4700监听...
  • java套接字编程笔记

    2017-06-07 22:00:29
    套接字编程笔记
  • 6、多路复用——select() 功能:用来检测一个或多个套接字状态。 格式:int PASCAL FAR select(int nfds,fd_set FAR * readfds,fd_set FAR * writefds, fd_set FAR * exceptfds,const struct timeval FAR * timeout)...
  • 套接字编程实验报告 本文关键词:编程,实验,报告套接字编程实验报告 本文简介:Programing实验物联2班201208080228赵智慧一、实验题目:利用套接字编程,编写出...importjava.io.IOExceptio套接字编程实验报告 本...
  • 简介套接字最初叫伯克利套接字,因为是由伯克利大学最初发明的。在Java中,可以很方便地调用Socket进行网络通信。下面,就试着用套接字向远程服务器进行读写数据。代码演示package demo0811.demo1;import java.io....
  • 计算机网络基础知识基于套接字的网路编程案例?什么是套接字?所谓socket通常也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄。应用程序通常通过"套接字"向网络发出请求或者应答网络请求。套接字可以根据...
  • JAVA UDP套接字编程

    2020-10-10 11:46:10
    JAVA UDP套接字编程 UDP套接字 无连接 非可靠传输 面向数据报 package com.lius.udp; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java...
  • java socket套接字编程

    2019-10-03 22:45:43
    java socket套接字编程 为了完成毕业设计学习了java套接字编程 1,socket服务端编写 在服务端上,需要新建一个套接字,监听是否有客户端进行连接,连接客户端,关闭服务端 首先你要知道有一个叫做 serversocket的...
  • 我打算用Java来运行模拟.我不认为我可以使用对象序列化来传递消息,因为我希望消息可以与其他语言实现的其他系统互操作,我认为使用序列化是不可能的.我可以在Java中使用哪些功能来与以不同语言实现的节点进行通信?...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 3,032
精华内容 1,212
关键字:

套接字编程java

java 订阅