java Socket客户端和服务器端

Posted jdsjlzx

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java Socket客户端和服务器端相关的知识,希望对你有一定的参考价值。


客户端:

package com.lzx.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import org.xml.sax.InputSource;

public class SocketClient

public static void main(String[] args)
new SocketClient();


public SocketClient()
try
Socket socket = new Socket("127.0.0.1", 9999);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
//接收键盘输入内容
System.out.println("enter some words : ");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line = reader.readLine();
out.println(line);

//接收服务器端的数据
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("reply from server : " + in.readLine());
catch (UnknownHostException e)
// TODO Auto-generated catch block
e.printStackTrace();
catch (IOException e)
// TODO Auto-generated catch block
e.printStackTrace();


 服务器:

package com.lzx.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;

public class SocketServer

public static void main(String[] args)
new SocketServer();


public SocketServer()
try
ServerSocket serverSocket = new ServerSocket(9999);
Socket socket = serverSocket.accept();
String remoteHost = serverSocket.getInetAddress().getHostName();
int remotePort = serverSocket.getLocalPort();//客户端端口
System.out.println("A client come, remoteHost :" + remoteHost + ", remotePort : " + remotePort);
//接收客户端的数据
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("received from client : " + reader.readLine());

//回复客户端
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("Tanks,I love you!");
catch (IOException e)
// TODO Auto-generated catch block
e.printStackTrace();


 

以上是关于java Socket客户端和服务器端的主要内容,如果未能解决你的问题,请参考以下文章

java服务器端用传输给客户端文件流(fileinputstream),客户端应该如何接收?(socket )

在java中如何用Socket 进行 服务器端和客户端交互的,具体一点。

java Socket客户端和服务器端

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

java socket 接收服务端的信息出现乱码,该怎么解决

Java 网络编程