导航:首页 > 编程语言 > java客户端与服务器通信

java客户端与服务器通信

发布时间:2024-08-01 17:36:56

『壹』 java网络编程,怎样在客户端和服务器间实现通信。

写个简单点的服务器跟客服端就行了我写了个很简单的,只能在一个客户端跟一个服务器通信,在控制台输入下面这个是服务器import java.io.*;
import java.net.*;
import java.util.Scanner;public class Server
{
public static void main(String[] args)
{
try {
ServerSocket server=new ServerSocket(8888);//定义客户端的端口号
Socket client=server.accept();//定义一个Socket对象

InputStream is=client.getInputStream();//服务器接受信息输入流,也就是接受从服务器段发送过来的消息
BufferedReader br=new BufferedReader(new InputStreamReader(is));//用bufferedreader包装下输入流

OutputStream os=client.getOutputStream();//这是用来给服务器发送消息的输出流
PrintStream ps=new PrintStream(os);
Scanner scanner=new Scanner(System.in);//从键盘输入字符串

boolean flag=true;//定义一个死循环,让服务器不停的接受从客户端发送来的字符串
while(flag)
{
String s=br.readLine();//s是从客户端接受到得字符串
System.out.println(s);

String s2=scanner.nextLine();//s2是写给客户端的字符串
ps.println(s2); //给客户端发送你写的东西
}
client.close();
} catch (IOException e) {//try 跟catch你不用管,这是用来处理异常的,就是固定格式

e.printStackTrace();
}
}
} 下面是客户端import java.io.*;
import java.net.*;
import java.util.Scanner;public class Client
{ public static void main(String[] args)
{
try
{
Socket client=new Socket("192.168.--.--",8888);//IP地址是个字符串,端口号是个整数,这个端口号要跟前面你写的那个一样,还有IP地址,写你的机器的IP地址

InputStream is=client.getInputStream();//这边的两个流跟上面服务器的差不多的作用
BufferedReader bf=new BufferedReader(new InputStreamReader(is));

OutputStream os=client.getOutputStream();
PrintStream ps=new PrintStream(os);
Scanner scanner=new Scanner(System.in);
boolean flag=true;
while(flag)//这句话可以让客户端不停的说话
{
String s2=scanner.nextLine();
ps.println(s2);

String s=bf.readLine();
System.out.println(s); }

client.close();

}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
} }}

『贰』 JAVA程序完成服务器和客户端的SOCKET通讯,要求服务器使用多线程接收和处理多个客户端访问请求

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多人聊天一般都是怎么搭建的

Java多人聊天可以使用Java的Socket编程实现,主要的思路是:使用服务器来维护所有客户端的连接,并将客户端之间的聊天信息进行转发。巧稿岁

具体的实现步骤如下:

import java.io.IOException;

import java.net.ServerSocket;

import java.net.Socket;

import java.util.ArrayList;

public class ChatServer {

private ServerSocket serverSocket;

private ArrayList<ClientHandler> clients;

public ChatServer(int port) throws IOException {

serverSocket = new ServerSocket(port);

clients = new ArrayList<ClientHandler>();

System.out.println("服务器已启动,等敬差待客户端连接...");

}

public void start() throws IOException {

while (true) {

Socket socket = serverSocket.accept();

ClientHandler client = new ClientHandler(socket, this);

clients.add(client);

client.start();

}

}

public void broadcast(String message) {

for (ClientHandler client : clients) {

client.sendMessage(message);

}

}

public void removeClient(ClientHandler client) {

clients.remove(client);

}

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

ChatServer server = new ChatServer(12345);

server.start();

}

}

客户端:

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.Socket;

public class ChatClient {

private Socket socket;

private BufferedReader reader;

private PrintWriter writer;

private String name;

public ChatClient(String serverAddress, int port, String name) throws IOException {

socket = new Socket(serverAddress, port);

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

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

this.name = name;

}

public void start() throws IOException {

System.out.println("欢迎来到聊天室!");

new Thread(new IncomingMessageHandler()).start();

new Thread(new OutgoingMessageHandler()).start();

}

private class IncomingMessageHandler implements Runnable {

@Override

public void run() {

try {

while (true) {

String message = reader.readLine();

if (message == null) {

break;

}

System.out.println(message);

}

} catch (IOException e) {

e.printStackTrace();

} finally {

close();

}

}

}

private class OutgoingMessageHandler implements Runnable {

@Override

public void run() {

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

try {

while (true) {

String message = reader.readLine();

if (message.equals("quit")) {

break;

}

writer.println(name + ": " + message);

}

} catch (IOException e) {

e.printStackTrace;

} finally {

close();

}

}

}

『肆』 JAVA TCP通信,客户端给服务器传送JAVA对象通信出错了,求各位大神指教

在java中用socket传输对象的时候,底层是把java对象序列化,然后以二进制数据进行传输的。socket的服务端和客户端都需要有这个对象的声明,比如客户端发送的是com.client.MsgPackage对象,那么这个对象的class文件必须在服务端的classpath中。否则就会是接收方接收了tcp的数据包,但是无法还原成对象。
底层要能把对象序列化,这个对象要实现一个可序列化的接口:java.io.Serializable。
类通过实现 java.io.Serializable
接口以启用其序列化功能。未实现此接口的类将无法使其任何状态序列化或反序列化。可序列化类的所有子类型本身都是可序列化的。序列化接口没有方法或字段,仅用于标识可序列化的语义。
writeObject 方法负责写入特定类的对象的状态,以便相应的 readObject 方法可以恢复它。通过调用
out.defaultWriteObject 可以调用保存 Object 的字段的默认机制。该方法本身不需要涉及属于其超类或子类的状态。通过使用
writeObject 方法或使用 DataOutput 支持的用于基本数据类型的方法将各个字段写入 ObjectOutputStream,状态可以被保存。
readObject 方法负责从流中读取并恢复类字段。它可以调用 in.defaultReadObject
来调用默认机制,以恢复对象的非静态和非瞬态字段。defaultReadObject
方法使用流中的信息来分配流中通过当前对象中相应指定字段保存的对象的字段。这用于处理类演化后需要添加新字段的情形。该方法本身不需要涉及属于其超类或子类的状态。通过使用
writeObject 方法或使用 DataOutput 支持的用于基本数据类型的方法将各个字段写入 ObjectOutputStream,状态可以被保存。

『伍』 java缃戠粶缂栫▼搴旇ユ庢牱鍦ㄥ㈡埛绔鍜屾湇鍔″櫒闂村疄鐜伴氫俊锛

浠ュ墠鍐欑殑锛岀収璐翠簡銆傘傘傛湇鍔″櫒绔锛歩mport java.awt.*;x0dx0aimport java.awt.event.WindowAdapter;x0dx0aimport java.awt.event.WindowEvent;x0dx0aimport java.io.*;x0dx0aimport java.net.*;/*6銆 閲囩敤UDP鍗忚锛岀紪鍐欎竴涓狫ava缃戠粶搴旂敤绋嬪簭锛岃ュ簲鐢ㄥ垎鏈嶅姟鍣ㄧ绋嬪簭鍜屽㈡埛绔绋嬪簭涓ら儴鍒嗐俓x0dx0a* 瀹㈡埛绔鎸囧畾涓涓鏈嶅姟鍣ㄤ笂鐨勬枃浠跺悕锛岃╂湇鍔″櫒鍙戝洖璇ユ枃浠剁殑鍐呭癸紝鎴栬呮彁绀烘枃浠朵笉瀛樺湪銆俓x0dx0a* 锛20鍒嗭級锛堟湇鍔$绋嬪簭鍜屽㈡埛绔绋嬪簭鍒嗗埆鍛藉悕涓篠erver.java鍜孋lient.java锛*/x0dx0apublic class N4BT6 extends Framex0dx0a{x0dx0aDatagramSocket socket ;x0dx0aDatagramPacket packet ;byte[] buf ;x0dx0aFile file ;x0dx0aFileInputStream input;x0dx0aString message = "璇ユ枃浠朵笉瀛樺湪";x0dx0aTextArea text;x0dx0apublic N4BT6(String title)x0dx0a{x0dx0asuper(title);x0dx0atext = new TextArea(6,4);x0dx0aadd(text);x0dx0asetSize(400, 300);x0dx0asetVisible(true);x0dx0aaddWindowListener(new WindowAdapter()x0dx0a{x0dx0apublic void windowClosing(WindowEvent e)x0dx0a{x0dx0adispose();x0dx0a}x0dx0a});x0dx0ax0dx0abuf = new byte[1024];x0dx0atryx0dx0a{x0dx0asocket = new DatagramSocket(1230);x0dx0apacket = new DatagramPacket(buf, buf.length);x0dx0asocket.receive(packet);x0dx0afile = new File(new String(packet.getData()));x0dx0asocket = new DatagramSocket();x0dx0a} x0dx0acatch (Exception e)x0dx0a{e.printStackTrace();x0dx0a}x0dx0ax0dx0aif(file.exists())x0dx0a{x0dx0atryx0dx0a{x0dx0abuf = new byte[(int)file.length()];x0dx0apacket = new DatagramPacket(buf,buf.length,InetAddress.getLocalHost(),1234);x0dx0ainput = new FileInputStream(file);x0dx0ainput.read(buf);x0dx0asocket.send(packet);x0dx0a}x0dx0acatch (IOException e) x0dx0a{x0dx0ae.printStackTrace();x0dx0a}x0dx0a}x0dx0aelsex0dx0a{x0dx0atryx0dx0a{x0dx0apacket = new DatagramPacket(message.getBytes(),message.getBytes().length,x0dx0aInetAddress.getLocalHost(),1234);x0dx0asocket.send(packet);x0dx0a}x0dx0acatch (Exception e) x0dx0a{x0dx0ae.printStackTrace();x0dx0a}x0dx0a}x0dx0ax0dx0a}x0dx0apublic static void main(String[] args)x0dx0a{x0dx0anew N4BT6("Server");x0dx0a}x0dx0a}x0dx0a瀹㈡埛绔锛歩mport java.awt.*;x0dx0aimport java.awt.event.*;x0dx0aimport java.net.DatagramPacket;x0dx0aimport java.net.DatagramSocket;x0dx0aimport java.net.InetAddress;public class N4BT6_2 extends Framex0dx0a{x0dx0aTextArea text;x0dx0aString message = "Q.txt";x0dx0aDatagramSocket socket ;x0dx0aDatagramPacket packet;x0dx0abyte[] buf;x0dx0apublic N4BT6_2(String title)x0dx0a{x0dx0asuper(title);x0dx0atext = new TextArea(6,4);x0dx0aadd(text);x0dx0asetSize(400, 300);x0dx0asetVisible(true);x0dx0aaddWindowListener(new WindowAdapter()x0dx0a{x0dx0apublic void windowClosing(WindowEvent e)x0dx0a{x0dx0adispose();x0dx0a}x0dx0a});x0dx0atryx0dx0a{x0dx0ax0dx0asocket = new DatagramSocket();x0dx0apacket = new DatagramPacket(message.getBytes(),message.getBytes().length,x0dx0aInetAddress.getLocalHost(),1230);x0dx0asocket.send(packet);x0dx0a}x0dx0acatch (Exception e) x0dx0a{x0dx0ae.printStackTrace();x0dx0a}x0dx0ax0dx0atryx0dx0a{x0dx0abuf = new byte[1024];x0dx0asocket = new DatagramSocket(1234);x0dx0apacket = new DatagramPacket(buf,buf.length);x0dx0asocket.receive(packet);x0dx0atext.append(new String(buf));x0dx0a}x0dx0acatch (Exception e) x0dx0a{x0dx0ae.printStackTrace();x0dx0a}x0dx0a}x0dx0apublic static void main(String[] args)x0dx0a{x0dx0anew N4BT6_2("Client");x0dx0a}x0dx0a}

『陆』 用Java socket 实现客户端与服务器之间的数据的发送与接受。。。双向的

下面是一个简单的通讯实例,进行Server和Client之间的文件传输。。如果是简单的文本传输的话简化掉文本操作的内容即可。。

1.服务器端

package sterning;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerTest {
int port = 8821;

void start() {
Socket s = null;
try {
ServerSocket ss = new ServerSocket(port);
while (true) {
// 选择进行传输的文件
String filePath = "D:\\lib.rar";
File fi = new File(filePath);

System.out.println("文件长度:" + (int) fi.length());

// public Socket accept() throws
// IOException侦听并接受到此套接字的连接。此方法在进行连接之前一直阻塞。

s = ss.accept();
System.out.println("建立socket链接");
DataInputStream dis = new DataInputStream(new BufferedInputStream(s.getInputStream()));
dis.readByte();

DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath)));
DataOutputStream ps = new DataOutputStream(s.getOutputStream());
//将文件名及长度传给客户端。这里要真正适用所有平台,例如中文名的处理,还需要加工,具体可以参见Think In Java 4th里有现成的代码。
ps.writeUTF(fi.getName());
ps.flush();
ps.writeLong((long) fi.length());
ps.flush();

int bufferSize = 8192;
byte[] buf = new byte[bufferSize];

while (true) {
int read = 0;
if (fis != null) {
read = fis.read(buf);
}

if (read == -1) {
break;
}
ps.write(buf, 0, read);
}
ps.flush();
// 注意关闭socket链接哦,不然客户端会等待server的数据过来,
// 直到socket超时,导致数据不完整。
fis.close();
s.close();
System.out.println("文件传输完成");
}

} catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String arg[]) {
new ServerTest().start();
}
}

2.socket的Util辅助类

package sterning;

import java.net.*;
import java.io.*;

public class ClientSocket {
private String ip;

private int port;

private Socket socket = null;

DataOutputStream out = null;

DataInputStream getMessageStream = null;

public ClientSocket(String ip, int port) {
this.ip = ip;
this.port = port;
}

/** *//**
* 创建socket连接
*
* @throws Exception
* exception
*/
public void CreateConnection() throws Exception {
try {
socket = new Socket(ip, port);
} catch (Exception e) {
e.printStackTrace();
if (socket != null)
socket.close();
throw e;
} finally {
}
}

public void sendMessage(String sendMessage) throws Exception {
try {
out = new DataOutputStream(socket.getOutputStream());
if (sendMessage.equals("Windows")) {
out.writeByte(0x1);
out.flush();
return;
}
if (sendMessage.equals("Unix")) {
out.writeByte(0x2);
out.flush();
return;
}
if (sendMessage.equals("Linux")) {
out.writeByte(0x3);
out.flush();
} else {
out.writeUTF(sendMessage);
out.flush();
}
} catch (Exception e) {
e.printStackTrace();
if (out != null)
out.close();
throw e;
} finally {
}
}

public DataInputStream getMessageStream() throws Exception {
try {
getMessageStream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
return getMessageStream;
} catch (Exception e) {
e.printStackTrace();
if (getMessageStream != null)
getMessageStream.close();
throw e;
} finally {
}
}

public void shutDownConnection() {
try {
if (out != null)
out.close();
if (getMessageStream != null)
getMessageStream.close();
if (socket != null)
socket.close();
} catch (Exception e) {

}
}
}

3.客户端

package sterning;

import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;

public class ClientTest {
private ClientSocket cs = null;

private String ip = "localhost";// 设置成服务器IP

private int port = 8821;

private String sendMessage = "Windwos";

public ClientTest() {
try {
if (createConnection()) {
sendMessage();
getMessage();
}

} catch (Exception ex) {
ex.printStackTrace();
}
}

private boolean createConnection() {
cs = new ClientSocket(ip, port);
try {
cs.CreateConnection();
System.out.print("连接服务器成功!" + "\n");
return true;
} catch (Exception e) {
System.out.print("连接服务器失败!" + "\n");
return false;
}

}

private void sendMessage() {
if (cs == null)
return;
try {
cs.sendMessage(sendMessage);
} catch (Exception e) {
System.out.print("发送消息失败!" + "\n");
}
}

private void getMessage() {
if (cs == null)
return;
DataInputStream inputStream = null;
try {
inputStream = cs.getMessageStream();
} catch (Exception e) {
System.out.print("接收消息缓存错误\n");
return;
}

try {
//本地保存路径,文件名会自动从服务器端继承而来。
String savePath = "E:\\";
int bufferSize = 8192;
byte[] buf = new byte[bufferSize];
int passedlen = 0;
long len=0;

savePath += inputStream.readUTF();
DataOutputStream fileOut = new DataOutputStream(new BufferedOutputStream(newBufferedOutputStream(new FileOutputStream(savePath))));
len = inputStream.readLong();

System.out.println("文件的长度为:" + len + "\n");
System.out.println("开始接收文件!" + "\n");

while (true) {
int read = 0;
if (inputStream != null) {
read = inputStream.read(buf);
}
passedlen += read;
if (read == -1) {
break;
}
//下面进度条本为图形界面的prograssBar做的,这里如果是打文件,可能会重复打印出一些相同的百分比
System.out.println("文件接收了" + (passedlen * 100/ len) + "%\n");
fileOut.write(buf, 0, read);
}
System.out.println("接收完成,文件存为" + savePath + "\n");

fileOut.close();
} catch (Exception e) {
System.out.println("接收消息错误" + "\n");
return;
}
}

public static void main(String arg[]) {
new ClientTest();
}
}

阅读全文

与java客户端与服务器通信相关的资料

热点内容
dtv网络电视手机版下载 浏览:954
mfc100u放在哪个文件夹 浏览:359
javaweb插件 浏览:58
pto密码忘记 浏览:567
logo竞赛教程 浏览:481
贵阳去哪里学编程比较好 浏览:132
java将string转为json 浏览:291
ppt2013制作exe文件 浏览:80
linux文件只读不能复制 浏览:597
开关代码 浏览:91
word绘图板 浏览:359
苹果minecraftpe注册 浏览:775
ps怎么存储文件卡 浏览:728
微信清除缓存图片恢复 浏览:305
安卓app会闪退怎么解决 浏览:429
哪些app背单词是免费的 浏览:889
cf击杀图标放哪个文件夹 浏览:208
为什么我的炉石不能查看完整数据 浏览:179
苹果7音量按键不回弹 浏览:296
u盘两个系统可以放一个文件夹吗 浏览:538

友情链接