자바 소켓 통신 및 TCP/UDP 구현
44048 단어 자바
TcpServer
public class TcpServer {
private static boolean isruning = true;
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(5583);
while (isruning) {
//
Socket socket = serverSocket.accept();
System.out
.println(" (" + socket.getInetAddress() + ") 。。");
OutputStream stream = socket.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(stream);
writer.write("hello socket!");
writer.flush();
writer.close();
System.out
.println(" (" + socket.getInetAddress() + ") 。。");
}
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
TcpClient
public class TcpClient {
public static void main(String[] args) {
String host = "localhost"; // IP
int port = 5583; //
try {
//
Socket client = new Socket(host, port);
InputStream inputStream = client.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(reader);
String message = bufferedReader.readLine();
System.out.println(message);
bufferedReader.close();
client.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
UdpSend
public class UdpSend {
public static void main(String[] args) {
MulticastSocket socket;
try {
socket = new MulticastSocket(8842);
socket.setTimeToLive(1);
InetAddress address = InetAddress.getByName("233.0.0.0");
socket.joinGroup(address);
byte[] buf = "hello world!".getBytes();
DatagramPacket p = new DatagramPacket(buf, buf.length, address,
8842);
socket.send(p);
System.out.println(" ");
} catch (IOException e) {
e.printStackTrace();
}
}
}
UdpReceive
public class UdpReceive {
public static void main(String[] args) {
MulticastSocket socket;
try {
socket = new MulticastSocket(8842);
socket.setTimeToLive(1);
InetAddress address = InetAddress.getByName("233.0.0.0");
socket.joinGroup(address);
byte[] buf = new byte[3000];
DatagramPacket p = new DatagramPacket(buf, buf.length);
socket.receive(p);
System.out.println(" " + p.getAddress() + " "
+ new String(p.getData()));
} catch (IOException e) {
e.printStackTrace();
}
}
}
2019 년 1 월 4 일 16:43:00 업데이트
나중에 이 루어 진 것 은 이전 버 전보 다 더 잘 붙 여 졌 다.
public class cfg {
public static String ip = "192.168.0.106";
public static int port = 8030;
}
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) {
try {
//
Socket client = new Socket(cfg.ip, cfg.port);
System.out.println(" !");
new Send(client).start();
new Recerver(client).start();
//socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;
import java.io.*;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
public class Recerver extends Thread {
Socket socket;
public Recerver(Socket client) {
this.socket = client;
}
@Override
public void run() {
super.run();
InputStream inputStream = null;
try {
inputStream = socket.getInputStream();
for (; ; ) {
DataInputStream stream = new DataInputStream(inputStream);
int head = -1;
while ((head = stream.read()) != 0xff) {
System.out.print("bad data");
}
System.out.print("head:" + head);
int len = stream.readInt();
byte[] data = new byte[len];
stream.read(data, 0, len);
String str = new String(data, Charset.forName("utf-8"));
System.out.println(socket.getInetAddress() + ":" + str);
}
} catch (IOException e) {
System.out.println(socket.getInetAddress() + " ");
}
}
}
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.Scanner;
public class Send extends Thread {
Socket socket;
public Send(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
super.run();
try {
OutputStream out = socket.getOutputStream();
Scanner scanner = new Scanner(System.in);
for (; ; ) {
String msg = scanner.nextLine();
byte[] content = msg.getBytes("utf-8");
ByteBuffer byteBuffer = ByteBuffer.allocate(content.length + 5);
byteBuffer.put((byte) 0xff);
byteBuffer.putInt(content.length);
byteBuffer.put(content);
out.write(byteBuffer.array());
out.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(cfg.port);
System.out.println(" :" + InetAddress.getLocalHost().getHostAddress() + ":" + serverSocket.getLocalPort());
for (; ; ) {
//
Socket socket = serverSocket.accept();
System.out
.println(" (" + socket.getInetAddress() + ") ");
new Send(socket).start();
new Recerver(socket).start();
}
//serverSocket.close();
} catch (IOException e) {
System.out.print(" :" + e.getMessage());
}
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.