「Java入門」簡単なsocketプログラム

1.サーバー側
package jsocket;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class JServer {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket=new ServerSocket(5000);
while(true){
Socket socket=serverSocket.accept();
InputStream is=socket.getInputStream();
byte b []=new byte [1024];
int length=0;
StringBuffer buffer=new StringBuffer();
while((length=is.read(b))!=-1){
String string=new String(b,0,length);
buffer.append(string);
}
System.out.println(“サーバー側の出力情報:"+buffer.reverse().toString());
}
}
}

2.client側
package jsocket;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

public class JClient {
public static void main(String[] args) throws Exception{
Socket socket=new Socket(“127.0.0.1",5000);
BufferedReader bufferedRead = new BufferedReader(new InputStreamReader(System.in));
OutputStream os=socket.getOutputStream();
os.write(bufferedRead.readLine().getBytes());
os.close();
}
}

Java

Posted by arkgame